簡體   English   中英

jQuery選擇li元素

[英]Jquery selecting li element

有一個listitem的問題,當我單擊所需的li時,它沒有執行任何操作。 現在,我只是讓它發出警報,所以我可以看到它在ive建立后可以從中獲得響應。

jQuery的

$('.propid').click(function(){
        alert($(this).find().attr('id'));
    });

的HTML

    <div>
    <form class='cform'>
      <div>
        Type in Property:
        <br />

        <input class="ui-corner-all" type="text" size="30" value="" id="inputString"  />

      </div>
      <div class="suggestionsBox" id="suggestions" style="display: none;">
        <div class="suggestionList" id="autoSuggestionsList">
          &nbsp;
        </div>
      </div>
    </form>
  </div>

在輸入內容時,adviceBox將顯示並填充ajax結果。

返回的html / php將附加到RecommendationionxBox中:

'<li class="propid" id="'.$result['roomnumber'].'">'.$result['name'].'</li>';

不知道為什么,當我一個li元素上點擊里面並不會提醒suggestionBox但是,如果使用

$('.suggestionBox').click(function(){
    alert($(this).find(li:first).attr('id'));
});

真棒的回答每個人,但我已經在html中分配了一個onclick事件:)

記住在AJAX調用完成后分配onclick事件。 僅在加載腳本時將其彈出到頁面上並不能確保所有將來/以后加載的元素也將附加事件處理程序。

簡單的例子:

$.ajax({
  type: "POST",
  url: "URL",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: "{'PARAM':'VALUE'}",
  success: function (result) {
    $("#autoSuggestionsList").append(result.d);
    $(".propid").click(function(){
        alert($(this).find().attr("id"));
    });
  }
});

嘗試

$('.propid').live("click",function(){
        alert($(this).find().attr('id'));
    });

$('.propid').click(function(){ ... }); 將在您的頁面上搜索具有“ propid”類的元素,並為其綁定點擊事件。 但是,如果在進行此綁定之后某些元素會出現-它們將無法工作(不會為它們進行綁定)。

這里有三種方式。

首先-在創建每個新元素之后進行綁定。 每次ajax調用之后$('.propid').unbind('.my_propid').bind('click.my_propid', function() { ... })類似: $('.propid').unbind('.my_propid').bind('click.my_propid', function() { ... }) (我使用了命名空間來避免兩次綁定)。

第二-為父元素進行綁定。 可以將javascript事件作為參數傳遞給綁定函數-這樣您就可以獲取事件的目標並確定-真正單擊了哪個子元素。 $('. suggestionsBox').click(function (e) { /* work with event e */ }); (http://feedproxy.google.com/~r/Bludice/~3/q0r9715M_JA/event-delegate-您可以在js中閱讀有關事件委托的更多信息)。

第三-是動態控制新元素(實時)。 $('.propid').live('click', function() { ... });

暫無
暫無

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

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