如何使用jquery定位来自innerHTML或.html()的元素集 [英] How to target elements set from innerHTML or .html() using jquery

查看:68
本文介绍了如何使用jquery定位来自innerHTML或.html()的元素集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其内容是从innerHTML动态生成的,我似乎无法使用jQuery进行验证来定位这些元素,例如,这是页面:

I have a div whose content gets dynamically generated from innerHTML and I cant seem to target those elements using jQuery for validation, Eg This is the page:

<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head>
</head>
<body>
<span id="alert1">Alert1</span>
<input type="button" value="Click Me" id="button1" />
<div id="empty"></div>
</body>
</html>

这是js代码:

<script type = "text/javascript"> 
    $(document).ready(function() {
         $('#button1').click(function() {
             var html = "uname <input type='text' id='uname'><br />password <input type='text' id='password'><br /><span id='alert'>Alert</span>";
             $('#empty').html(html);
         });
         $('#alert').click(function() {
             alert('Alert');
         });
         $('#alert1').click(function() {
             alert('Alert1');
         });
    });
</script>​

具有id alert1的范围的警报有效,但使用innerHTML或.html()设置的id警报无效,那么如何解决此问题?

The alert for the span with id alert1 works but for id alert which is set using innerHTML or .html() does not work so how to fix this?

预先感谢您

推荐答案

这里的问题是当您这样编写时..

The problem here is that when you write like this..

    $("#element").click(function() {
        alert("Alert!");
    });

..它只会为执行代码时存在的元素创建事件处理程序.即使它们具有相同的jQuery选择器(在本例中为"#element"),它也不会为将来的元素创建事件处理程序.

.. it will only create events handlers for elements that exist when you execute the code. It won't create event handlers for future elements even if they have the same jQuery selector ("#element" in this case).

您需要做的是在父元素上绑定 .on(事件,选择器,函数),因为事件会破坏"层次结构.这样,您可以处理来自指定选择器的将来事件.我个人会这样:

What you need to do is bind with .on(event, selector, function) on a parent element, as the events "bubble up" the hierarchy. That way you can handle future events from the specified selector. Personally I would do it like this:

$(document).ready(function() {
     $('#button1').click(function() {
         var html = "<insert lots of html stuff here>";
         $('#empty').html(html);
    });

    $(document).on("click", "#alert", function() {
        alert("Alert!");
    });

    $(document).on("click", "#alert1", function() {
        alert("Alert1!");
    });
});​

这篇关于如何使用jquery定位来自innerHTML或.html()的元素集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆