通过jQuery的.after方法更改正在加载的div的值/内容。

huangapple go评论69阅读模式
英文:

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

&lt;button class=&quot;btn123&quot; id=&quot;btn&quot;&gt;Click Here&lt;/button&gt;

jQuery

$(document).ready(function()
{
   $(&#39;.btn123&#39;).after(&#39;&lt;br/&gt;&lt;div id=&quot;textNi&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;georgia&amp;quot; , 
               &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;&lt;span style=&quot;color: #660000;&quot;&gt;Sample ra 
               ni&lt;/span&gt;&lt;/div&gt;&lt;/span&gt;&#39;);
});

$(&#39;#btn&#39;).on(&#39;click&#39;, &#39;#textNi&#39;, 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&mdash;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:

$(&#39;#btn&#39;).on(&#39;click&#39;, function() {
   $(&#39;#textNi&#39;).text(Math.random().toString(36).substring(7));
});

答案2

得分: 1

我已编辑了代码:

$(&#39;#btn&#39;).on(&#39;click&#39;, function()
{
	$(&#39;#textNi&#39;).text(Math.random().toString(36).substring(7));
});
英文:

I have edited the code:

$(&#39;#btn&#39;).on(&#39;click&#39;, function()
{
	$(&#39;#textNi&#39;).text(Math.random().toString(36).substring(7));
});

huangapple
  • 本文由 发表于 2020年1月6日 20:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定