英文:
Change value/content of div that is being loaded through .after method in jquery
问题
我知道这是一个简单的问题,但我在解决这个问题上遇到了困难。
按钮元素下面的文本是在DOM加载后生成的。点击按钮后,输出应该有一个随机字符串。我学到了应该使用事件委托来绑定事件,这就是我使用"on"方法的原因。然而,我的代码不起作用。
这是jsfiddle。
HTML
<button class="btn123" id="btn">点击这里</button>
jQuery
$(document).ready(function() {
$('.btn123').after('<br/><div id="textNi"><span style="font-family: \'georgia\', \'times new roman\', serif;"><span style="color: #660000;">这是示例文本</span></div></span>');
});
$('#btn').on('click', '#textNi', function() {
$(this).text(Math.random().toString(36).substring(7));
});
英文:
I know this is a simple question, but I got a hard time solving this one.
The text below the button element is generated after the DOM is loaded. The output should have a random string after a button is clicked. I learned that delegation binding should use, that's why I'm using the "on" method. However, my code doesn't work.
Here's the jsfiddle
HTML
<button class="btn123" id="btn">Click Here</button>
jQuery
$(document).ready(function()
{
$('.btn123').after('<br/><div id="textNi"><span style="font-family: &quot;georgia&quot; ,
&quot;times new roman&quot; , serif;"><span style="color: #660000;">Sample ra
ni</span></div></span>');
});
$('#btn').on('click', '#textNi', function()
{
$(this).text(Math.random().toString(36).substring(7));
});
答案1
得分: 2
#textNi
不是 #btn
中找到的后代,而是一个同级元素,因此你的回调函数永远不会触发。如果查看 .on()
文档,它说第二个参数是:
用于过滤触发事件的所选元素的后代的选择器字符串。
你可以直接选择 #textNi
:
$('#btn').on('click', function() {
$('#textNi').text(Math.random().toString(36).substring(7));
});
英文:
Your generated markup will look something like this:
└┬ #btn
└ #textNi
#textNi
is not a descendant that is found in #btn
, but it is instead a sibling—therefore, your callback will never fire. If you look up the .on()
documentation, it says that the second argument is:
> A selector string to filter the descendants of the selected elements that trigger the event.
You simply select for #textNi
directly instead:
$('#btn').on('click', function() {
$('#textNi').text(Math.random().toString(36).substring(7));
});
答案2
得分: 1
我已编辑了代码:
$('#btn').on('click', function()
{
$('#textNi').text(Math.random().toString(36).substring(7));
});
英文:
I have edited the code:
$('#btn').on('click', function()
{
$('#textNi').text(Math.random().toString(36).substring(7));
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论