dongwai4434 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.

<script>    
$(document).ready(function(){
    $(".subnetkey").click(function() {
        alert("subnet click mode");
    });
});
</script>

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?

</div>
  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没法联网
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e