简体   繁体   English

您可以在JS字符串打印的HTML标签上使用jQuery选择器吗?

[英]Can you use a jQuery selector on a HTML tag that a JS string printed?

Sorry if the question was misleading, I couldn't find a better way to describe my problem. 抱歉,如果该问题引起误解,我找不到更好的方式来描述我的问题。 Anyway, here goes: 无论如何,这里是这样:

Suppose I had a button start that initially displays a string for me. 假设我有一个按钮start ,最初为我显示了一个字符串。 Said string (let's call it stringA ) is output through jQuery like this: 所说的字符串(我们称它为stringA )是通过jQuery这样输出的:

$(".start").click(function() {
    $(".startButton").hide('slow', function() {
        $("#table1").html(stringA);
    });
});

Alright. 好的。 Cool. 凉。 That worked without a hitch. 一切顺利。 Now inside stringA I have multiple 现在在stringA我有多个
<span class="optButton">this is a button</span> buttons. <span class="optButton">this is a button</span>按钮。 I have another onClick handler for my optButton button, and it goes like this: 我的optButton按钮有另一个onClick处理程序,它像这样:

$(".optButton").click(function() {
    alert("Testing");
    $("#table1").html(stringB);
});

Needless to say, clicking on optButton is supposed to replace the contents of #table1 with stringB . 不用说,单击optButton应该用stringB替换#table1的内容。 However, when I tried it, it doesn't work. 但是,当我尝试时,它不起作用。 I tried adding alert() to test and see if jQuery managed to select optButton , but it seems that it didn't because I get no popup from the alert() function. 我尝试添加alert()进行测试,以查看jQuery是否成功选择了optButton ,但是似乎没有,因为我没有从alert()函数中看到弹出窗口。

My theory is that since optButton was not part of the original HTML and is within a string stringA , jQuery is unable to select optButton as a result. 我的理论是,由于optButton不属于原始HTML且位于字符串stringA ,因此jQuery无法选择optButton If this is true, is there a workaround to this issue? 如果是这样,是否有解决此问题的方法? If it is not, what is the actual cause of the problem here? 如果不是,这里的实际原因是什么?

You need to use event delegation since your span element has been dynamically added to the DOM: 您需要使用事件委托,因为您的span元素已动态添加到DOM中:

$('#table1').on('click', '.optButton', function() {
    alert("Testing");
    $("#table1").html(stringB);
});

This technique will helps you to attach click handler to these newly created span elements. 此技术将帮助您将点击处理程序附加到这些新创建的span元素上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM