我对 JS 和 JQuery 还是有点陌生,所以请原谅这个可能是一个简单而愚蠢的问题。
背景:
我的页面上有一个 div,其中包含多个 div (#idle-variable)。单击顶级 div 时,它基本上显示其他 div (#addvariable)。无非就是显示:无;和.show()。简单的。在该 div 中的另一个操作(更改下拉列表)中,我本质上想在第一个实例下方注入(inject)/插入顶级 div (#idle-variable)。
问题:
本质上,.click 函数不适用于我新插入的 div。这可能是因为两个 div 共享相同的 ID,但我偷偷怀疑它在 DOM 中未被识别。我的一个 friend 说我必须“重新运行”我的 jquery 才能使其在 DOM 中可读。
问题:
我怎样才能让它正常工作?我希望能够向页面添加动态数量的空闲变量,并且我需要确保我的 .click 函数适用于所有添加的 DIVS。
$(function(){
$('#idle-variable').click(function(event) {
$("#addvariable").show(400);
});
});
//create variable in db & show value entry
$("#variabletype").change(function() {
$("#varholder").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/myphpfile.php",
data: {"variabletype": $("#variabletype").val()},
success: function(){
$( "#idle-variable" ).after("<div id="#idle-variable>content</div>");
}
});
});
最佳答案
为了使代码正常工作,需要使用 on 并且 ids 只能在一个元素上。如果它可以多次出现在页面上,则需要使用类。
$(document).on("click,'#idle-variable', function(event) {
$("#addvariable").show(400);
});
你应该使用类
$(document).on("click,'.idle-variable', function(event) {
//$("#addvariable").show(400); //not sure how this relates to the clicked element.
$(this).find(".addvariable").show(400); //if it is a child
});
您的代码中还有一个带有引号的拼写错误。
关于javascript - JQuery 不适用于插入/注入(inject) DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891720/