簡體   English   中英

在html中動態添加事件監聽器

[英]Dynamically adding event listener in html

我在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時添加新的事件偵聽器,但我一直在努力尋找實現此目的的最佳方法。

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

您不能將click事件嵌套在click事件中。 另外,您需要使用on()將click事件綁定到動態內容:

JS小提琴

$(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();
});

如果要將事件偵聽器綁定到動態創建的元素,則需要使用jQuery.on ,例如$("#userList").on("click", "li", function(){ ... });

希望能幫助到你。

只要不動態定義功能,是否使用“ on”並不重要:

$('#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));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM