不能用Jquery从$.get() / $.load()函数中选择ID.请帮帮我

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

本文关键字:选择 ID 函数 Jquery get 不能 load      更新时间:2023-09-26

我的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>

当button LOAD被点击时,html将是这样的

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

但是,当我点击div id-from-data-load时,函数不会运行。

如何解决?

您需要为div事件使用live。应该是这样的:

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

try:

$('#id-from-data-that-load').live("click", function() {
                  alert($(this).attr("id");
                });

您需要将事件绑定到运行时通过.live处理程序或.delegate处理程序加载的元素。这是因为当您将事件绑定到元素时,它们并不存在于dom中。live和delegate能帮你实现这个。参见@shree的答案

中的示例

在内容中加载数据后绑定id-from-data-that-load。

  $('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>