簡體   English   中英

無法通過$ .get()/ $ .load()函數使用Jquery選擇ID。 請幫我?

[英]Cannot select ID with Jquery from $.get() / $.load() function. Please Help Me?

我的Javascript是這樣的

$('button').click(function(){
  //load the data and place inside to #content
});

$('#id-from-data-that-load').click(function(){
  //Do some action
});

這是html標記

<button>Load</button>
<div id="content">
  //Empty Data
</div>

當按鈕加載單擊html時將是這樣

<button>Load</button>
<div id="content">
  <div id="id-from-data-that-load">
    content that load
  </div>
</div>

但是,當我單擊div id-from-data-load時,該功能將無法運行。

怎么解決呢?

您需要將live用於div事件。 應該是這樣的:

$('#id-from-data-that-load').live("click", function(){
  //Do some action
});

或者,您也可以這樣做:

var submitted = false;

$('button').click(function(){
  // If the button was clicked before, we don't submit again.
  if (submitted == true) { return false; }

  // Set submitted to true, so when user clicks the button again,
  // this operation will not be processed one more time.
  submitted = true;

  //load the data and place inside to #content
  $.post("/getdata", {}, function(response) {
      //after the load happened we will insert the data into the div.
      $("#content").html(response);

      // Do the bindings here.
      $('#id-from-data-that-load').click(function(){
        //Do some action
      });
  });

  return false;
});

嘗試:

$('#id-from-data-that-load').live("click", function() {

                  alert($(this).attr("id");

                });

您需要通過.live處理程序或.delegate處理程序將事件綁定到在運行時加載的元素。 那是因為當您將事件綁定到元素時,它們不在dom中。 因此.live和.delegate將幫助您實現這一目標。 請參閱@shree的答案中的示例

在內容中加載數據后,綁定從加載的數據ID。

  $('button').click(function(){
      //load the data and place inside to #content
      $('#id-from-data-that-load').click(function(){
        //Do some action
     });
    });

綁定LI時,您可以將函數名稱硬編碼到onclick屬性中。

<li onclick="myFunction">Blah Blah Blah</li>

暫無
暫無

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

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