简体   繁体   中英

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

My Javascript something like this

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

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

So this is html tag

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

when button LOAD clicked html will be like this

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

BUT, when i clicked div id-from-data-load the function won't run.

How to solve it?

You need to use live for the div event instead. Here's what it should be:

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

Or alternatively you could also do this:

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");

                });

you need to bind events to elements loaded at runtime through either the .live handler or .delegate handler. That is because when you are binding events to elements they are not present on the dom. So .live and .delegate would help you achieve that. See example from @shree's answer

Bind id-from-data-that-load after data load in content.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM