在 JavaScript 中将值导入动态变量时出现问题

Problems getting values into a dynamic variable in javascript

本文关键字:变量 问题 动态 导入 JavaScript      更新时间:2023-09-26

selectedsongdiv 与不同的 rel="...问题是...

我正在使用它:

selectedBtn = $('#selectedsong a');
selectedBtn.click(function()
{
    self.selectedsong($(this).attr('rel'));
    return false;
});
selectedsong: function(number)
{
    $('#selectedsong').html('new content with new links, rel, and more...');
    selectedBtn = $('#selectedsong a'); <---- THE PROBLEM IS HERE,
}

问题是,在第一次点击中它工作正常,但是当 #selectedsong 内容发生变化时,selectedBtn = $('#selectedsong a'); 不能正常工作,因为 selectedBtn.click(function() 不起作用:'(

谢谢!

使用

$('#selectedsong').on('click','a',function(e)
{
    e.preventDefault(); // prevent default behavior of anchor click
    self.selectedsong($(this).attr('rel'));
    //return false;  dont use return false as it does more work than you need
});
selectedsong: function(number) 
{
  $('#selectedsong').html('new content with new links, rel, and more...');
}

当 HTML 内容更改时,需要使用事件委派。

阅读更多关于 .on() 的信息

我认为

问题是您在#selectedsong内更改了html,并从中删除了<a>标签,这就是您尝试进行选择的,是#selectedsong内部的<a>标签。也许您可以尝试只选择#selectedsong而不是锚标签?或者当您更改 html 时,请更改 #selectedsong a 的 html 。