在html中动态添加事件侦听器

时间:2016-09-08 03:32:36

标签: javascript jquery html css

我有两个HTML格式的UL,一个用于用户,一个用于共享用户。

<div class="container">

    <div id="userList" style=" ;width:45%;margin:10px;display:inline-block;vertical-align: top;">
       <span>Users</span>
       <ul class="usersUL">
         <li title="Add user"><a href="#">user1</a></li>
         <li title="Add user"><a href="#">user2</a></li>
       </ul>
   </div>

   <div id="sharedUsers"style="width:45%;margin:10px;display:inline-block;vertical-align: top;">
     <span>Shared Users</span>
     <ul class="usersUL" >

     </ul>
   </div>
 </div>

我想将UL中的li添加到用户点击的第二个列表中,反之亦然。我这样做的方式就是这样

    //add to shared users from userslist
    $("#userList li").click(function(){

       $("#sharedUsers ul").append('<li title="Remove user">'+$(this).html()+'</li>');

    //add to users list from shared users
       $("#sharedUsers li").click(function(){
          $("#userList ul").append('<li title="Add user">'+$(this).html()+'</li>');
          $(this).remove();
          });
       $(this).remove();
       });

我知道我做错了什么,我没有添加新的事件监听器一旦列表项从第二个UL发送回第一个UL.But我很难找到我能做到的最佳方式。

这是js小提琴:https://jsfiddle.net/4n7Ly4r2/

3 个答案:

答案 0 :(得分:3)

您无法在点击事件中嵌套点击事件。此外,您需要使用on()

将click事件绑定到动态内容

JS Fiddle

$(document).on('click', '#userList li', function() {    
  $("#sharedUsers ul").append('<li title="Remove user">' + $(this).html() + '</li>');      
  $(this).remove();
});

$(document).on('click', '#sharedUsers li', function() {    
  $("#userList ul").append('<li title="Add user">' + $(this).html() + '</li>');
  $(this).remove();
});

答案 1 :(得分:1)

如果要将事件侦听器绑定到动态创建的元素,则需要使用jQuery.on,例如$("#userList").on("click", "li", function(){ ... });

希望它有所帮助。

答案 2 :(得分:1)

使用&#39; on&#39;或者不重要,只要不动态定义功能:

$('#userList li').click(relocLi);
$('#sharedUsers li').click(relocLi);

function relocLi() {
  if ($(this).attr('title') == "Add user") {
    $(this).attr('title', 'Remove user');
    $("#sharedUsers ul").append($(this));
  } else {
    $(this).attr('title', 'Add user');
    $("#userList ul").append($(this));
  }
}
相关问题