问题描述
我想在jquery click事件之外显示“ mp3Url”变量。其实是否可以从下面的代码片段中找到?我看到了很多文章,但是没有用。
<script>
var mp3Url;
// Now I CLICK album-poster TO GET CURRENT SONG ID
$(".album-poster").on('click',function(e){
mp3Url = $(this).attr('data-mp3');
});
//console.log( mp3Url );
const ap = new APlayer({
container: document.getElementById('aplayer'),listFolded: true,audio: [
{
name: 'Invisible Beauty',artist: 'Artist',url: mp3Url,// Here is the variable
cover: 'photo.jpg'
},]
});
</script>
解决方法
这取决于您何时显示它。在当前表单中,您的脚本可以完成三件事,
1. Declare mp3Url variable (no value assigned)
2. Create and register a function to be execute whenever album poster is clicked.
a. Assign a value to the variable above (whenever the poster is clicked).
3. Print value of the above variable to console.
在步骤2中,您刚刚创建了一个函数,并“注册”了该函数以响应将来的某些事件而执行。执行步骤3时,mp3Url
变量仍将具有undefined
值,因为浏览器将立即一起运行步骤1、2、3,而不会给用户提供任何单击的机会。稍后,每当用户单击海报时,将执行2系列的子步骤。
如果要在“用户单击海报时”打印该值,只需在事件处理函数内部移动控制台语句。这是必需的,因为浏览器将仅在用户操作时运行在事件处理程序中编写的代码。
PS:在使用它时,您也可以在事件处理程序内移动变量。
,尝试此操作,在声明APlayer不存在的情况下mp3Url不存在
var ap;
$(".album-poster").on('click',function(e){
var mp3Url = $(this).attr('data-mp3');
ap = new APlayer({
container: document.getElementById('aplayer'),listFolded: true,audio: [
{
name: 'Invisible Beauty',artist: 'Artist',url: mp3Url,// Here is the variable
cover: 'photo.jpg'
},]
});
});