douju1997 2013-06-18 23:58
浏览 112
已采纳

如何在动态生成的div中定位Jquery .load函数

short: How do you use the Jquery .load function inside a dynamically generated div, but target a non clicked ID.

The idea is that I have a button that adds new divs every time clicked with "name+(sequential id") using the "$().append()" feature of jquery. Once the Div is added to the page a "$().load()" fills the div with two select boxes and another div.

Once loaded the user is able to use the first select box to select a value.

When value is selected the "$().on('click'" feature in Jquery checks too see if it was first option box is clicked and changed.

At this point after the first option box is selected and changed a "().load()" is used to update "#ajax-load-1" div surrounding the second option box. This is where i cannot get the ".load" to see the ID of the div.

I have done many a search and come up empty handed, a lot of tutorials on how to use .on("click" to get a ID of an element that was dynamically generated but not one that wasn't clicked.

Here is a simplified example of the code described above.

Html:

<!-- |This box has been dynamically generated and named through a Jquery .load() | -->

<div id="dynamic-box-1">

<select id="select-1">

    <option>1</option>

    <option>2</option>

</select>

<!-- | div to be .load()'ed after an option is selected in #select-1 |-->
<div id="ajax-load-1">

    <select id="ajax-select-1">

        <option>1</option>

        <option>2</option>

    </select>

</div>

</div>

<!-- | End of dynamic box | -->

Jquery

$("#select-1").on("click", function(){

$("#select-1").change(function(){

       $("#ajax-load-1").load("../php/ajax-load-1.php");

});

});
  • 写回答

1条回答 默认 最新

  • duanche2007 2013-06-19 00:15
    关注

    Try using event delegation

    Replace

    $("#select-1").change(function(){
    

    with

    $(document).on('change', '#select-1', function(){
    

    And remove the click event encasing it.

    If the HTML you have provided is the one you expect to see in the application. then you can get the id of the div with something like this

     $(document).on('change', '#select-1', function(){
         var divId = $(this).next('div').attr('id');
         $("#" + divId ).load("../php/" + divId + '"php");
     });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?