简体   繁体   English

在jquery中为子子节点添加事件

[英]add event for sub children in jquery

Just a little help for me here with jquery. 在这里用jquery给我一点帮助。 This is my problem. 这是我的问题。 I have a list 我有一份清单

<ul>
  <li>
      <p>Name</p>
      <a href="#">Delete</a>
  </li>
</ul>

the 'Delete' event click was initiation in jquery when load page. 加载页面时,“删除”事件单击是在jquery中启动的。 So the issue now, i'd like to add an element <li></li> which contain children like above. 所以现在问题,我想添加一个元素<li></li> ,其中包含上面的子项。 I used jquery to create the tag 'li' contain children, then 'prepend' to the 'ul'. 我使用jquery创建标签'li'包含子项,然后'prepend'到'ul'。 The problem is, i can not call 'delete' event on new item. 问题是,我不能在新项目上调用'删除'事件。 Somebody help me please 请有人帮帮我

The problem is that you're most probably using .click or bind('click') to attach the click event handler to the element. 问题是你最有可能使用.click或bind('click')将click事件处理程序附加到元素。 This is fine if all of the elements exist at the time when you attach the event, if however you create new elements that match that same selector, they will not get that event attached. 如果在附加事件时存在所有元素,那么这很好,如果您创建与该相同选择器匹配的新元素,则它们不会附加该事件。

You need to use the delegate() or .on() method to attach the event to all elements that are current on the page or are appended to the page after they're set up. 您需要使用delegate()或.on()方法将事件附加到页面上当前的所有元素,或者在设置后附加到页面。

An example of a delegate that catches the click event and appends a new element that you can click and see that the same event is attached to each new part of the DOM that matches the selector. 捕获click事件并附加新元素的委托示例,您可以单击该元素并查看相同事件是否附加到与选择器匹配的DOM的每个新部分。

$('#list').delegate('a','click',function() {
    alert('Click event fired - Adding a new element to test!');
    $('ul').append('<li><p>Name</p><a href="#">Delete</a></li>');
    return false;
});

Or using the newer .on method: 或者使用较新的.on方法:

$('#list').on('click','a',function() {
    alert('Click event fired - Adding a new element to test!');
    $('ul').append('<li><p>Name</p><a href="#">Delete</a></li>');
    return false;
});

$('#list') is what my example uses to denote the <ul> , but you could just as easily use $('ul') if you don't want to put an id or class on the list. $('#list')是我的例子用来表示<ul> ,但如果你不想在列表中放置id或类,你可以很容易地使用$('ul')

Example Fiddle 示例小提琴

try this DEMO 试试这个DEMO

var contentToAdd = ' <li> <p>Name</p> <a href="#">Delete</a> </li>';
$('ul').prepend(contentToAdd);

$('ul').on('click','a', function(){
    alert('click');
});

take a look at this jQuery example: 看看这个jQuery示例:
(one of the last examples on http://api.jquery.com/on/ ) http://api.jquery.com/on/上的最后一个例子之一)

<!DOCTYPE html>
<html>
<head>
  <style>
p { background:yellow; font-weight:bold; cursor:pointer;
    padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <p>Click me!</p>
<span></span>
<script>
var count = 0;
$("body").on("click", "p", function(){
  $(this).after("<p>Another paragraph! "+(++count)+"</p>");
});
</script>

</body>
</html>

which means in your case you need something like: 这意味着在你的情况下你需要这样的东西:

$("ul").on("click", "a", function(e){
    // delete logic goes here
})

Add the click listener on the UL rather than the a's themselves. 在UL上添加点击监听器而不是a本身。 This way it will automatically detect clicks to newly added items as well. 这样,它也会自动检测新添加项目的点击次数。

$(document).ready(function() {
    $("ul").on("click li > a", function() {
        $(this).closest("li").remove();
    });
});

You can use the .on() method to do so, 您可以使用.on()方法来执行此操作,

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object .on()方法将事件处理程序附加到jQuery对象中当前选定的元素集

$(document).on("click", "ul li a"), function(){
    //your code here
});

Test Link 测试链接

Okay, given that ".on" doesn't meet your requirements, perhaps something like: 好的,鉴于“.on”不符合您的要求,可能是这样的:

$element = $('<li><p>Name</p><a href="#">Delete</a></li>');
$element.find("a").click(function(){ 
    //call your delete function
})

$("ul").prepend($element);

You can try this, 你可以试试这个,

$("ul").on("click", "a", function(e){
    e.preventDefault();
    $(this).closest('li').remove();
});
Why dont you use jquery templating.
You can define a text/template and iterate over it to get your desired result.
an example:
**THIS IS YOUR SCRIPT**
<script id="movieTemplate" type="text/x-jquery-tmpl">
    <li><b>${Name}</b> was released in ${ReleaseYear}.</li>
</script>

**THIS IS THE JQUERY TEMPLATE**
<script type="text/javascript">
    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

    // Render the template with the movies data and insert
    // the rendered HTML under the "movieList" element
    $( "#movieTemplate" ).tmpl( movies )
        .appendTo( "#movieList" );
</script>

**THIS IS YOUR HTML**
<ul id="movieList"></ul>

More examples : http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/ 更多示例: http//blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM