2018-08-14 20:48
采纳率: 0%
浏览 39

单击<span>标签运行JQuery javascript函数[重复]

This question already has an answer here:

I create a span using PHP like this.

if ($subnetkey  == 1 ) { echo ("<span class='subnetkey'>S/N of: $subnetnum</span>&nbsp;&nbsp;");}

It works, and shows the correct data on screen. Additionally if I look at it using 'Inspect Element' its properly formatted.

<span class="subnetkey">S/N of: 780</span>

I have this script at the top of the page. I've also tried it at the bottom.

    $(".subnetkey").click(function() {
        alert("subnet click mode");

When I click the span, nothing happens. I get no errors, and of course I don't see the alert fire.

It seems like this is a timing issue between building the page dynamically and using the page. But in case thats not it, what can I do to make the function fire?


图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • 动态创建元素的事件绑定? 23 answers


     <  code> if($ subnetkey == 1){echo(“&lt; span class ='subnetkey'&gt; S / N of:$ subnetnum&lt; / span&gt;&amp; nbsp;&amp; nbsp;”);} 
     <  / code>  

    它可以工作,并在屏幕上显示正确的数据。 另外,如果我使用'Inspect Element'查看它,它的格式正确。

     &lt; span class =“subnetkey”&gt; S / N of:780&lt; / span&gt; 

    我在页面顶部有这个脚本。 我也在底部尝试过。

     &lt; script&gt;  
    &lt; / script&gt; 

    单击跨度时,没有任何反应。 我没有错误,当然我没有看到警报火。

    这似乎是动态构建页面和使用页面之间的时间问题。 但是,如果不是这样,我该怎么做才能使该功能解决?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douling8772 2018-08-14 21:03

    JQuery Event Methods like click(), dblclick(), mouseenter() etc. work only for elements already created when DOM is rendered. For dynamically created elements you use on() method with the below syntax (see previous post):

    $(staticAncestors).on(eventName, dynamicChild, function() {});

    Since it is a dynamically created element your code won't work. Try:

    $(document).on('click', '.subnetkey', function() {
        alert("subnet click mode");

    jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use event delegation, bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally you should delegate to the nearest parent existing at the time of page load.

    解决 无用
    打赏 举报

相关推荐 更多相似问题