一组动态元素的委托事件处理程序

时间:2013-08-07 08:07:04

标签: javascript ajax jquery

我的JS如下:

$(document).ready(function(){
    $('#data1').change(function(){
        title = $('#title1').val();
        url = $('#url1').val();
        $.post('library/edit.php',{title:title, url:url},function(res){
            alert ("updated !");
        });
    });
});

和我的HMTL标记:

<div id="data1">
<input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" />
</div>

我编写了该代码,用于在更改文本框时调用PHP文件。 该代码按预期工作。

但是现在我添加了更多文本框,如下所示:

<div id="div1"><input name="title1" type="text" id="title1" />
<input name="url1" type="text" id="url1" /></div>
<div id="div2"><input name="title2" type="text" id="title2" />
<input name="url2" type="text" id="url2" /></div>
<div id="div3"><input name="title3" type="text" id="title3" />
<input name="url3" type="text" id="url3" /></div>

现在我想要相同的功能,以便任何这些文本框在我之前的代码中都像title1一样工作。因此,如果输入#title-3被更改,我希望通过POST将更改上传到我的PHP脚本。

重要提示:框数是动态的。

3 个答案:

答案 0 :(得分:2)

$(document).ready(function(){
$('#data1').on('change','[id^=title],[id^=url]',function(){

    var index = $(this).attr('id').replace('title',"").replace('url',"");

    var title = $("#title" + index).val();
    var url = $("#url" + index).val();
    var hid = $("#hid" + index).val();
    // you can put in here in sequence all the fields you have
    $.post('library/edit.php',{title:title, url:url, hid : hid},function(res){
        alert ("updated !");
    });
});

});

所以,如果任何文本框的标题符号以标题更改开头,则通过此答案。 传入的函数将被调用。 indezx变量将存储正在更改的元素组的索引。然后通过从title1或title2

中删除标题来调用

答案 1 :(得分:0)

我认为答案就在这里:

  

我编写了该代码,用于在更改文本框时调用php文件。

该脚本(我猜是jQuery)它必须与$('#xxx1').onchange()权利相关联? (或类似的)
如果您修改了该函数,请在输入字段中添加一个类(也在php中),每次调用该函数时,再次开始监听。我认为您可以调用任何您想要的函数。

示例(猜测您的代码)

HTML

<div id="data1" class="dynamicDiv">
  <input name="title1" type="text" id="title1" />
  <input name="url1" type="text" id="url1" />
</div>

的jQuery

// enable the function on document ready
$(document).ready(function(){
  startListening('.dynamicDiv');
});

// each time an ajax call is completed,
// run the function again to map new objects
$(document).ajaxComplete(function(){
  startListening('.dynamicDiv');
});

// and finally the function
function startListening(obj){
  $(obj).onchange(function(){
    // ajax call
    // function call
    // or whatever...
  });
}

PHP

// some code....
// some code....
// remember here to add "dynamicDiv" as a class in the object
return object;

答案 2 :(得分:-1)

由于您的元素是动态生成的,您需要使用事件委派,然后您可以使用[id^="value"]根据其id属性的第一部分选择适当的元素

$(document).ready(function(){
    $(document).on('change','[id^="data"]',function(){
        var title = $(this).find('[id^="title"]').val();
        var url = $(this).find('[id^="url"]').val();
        var hidden = $(this).find('[id^="hid"]').val();
        $.post('library/edit.php',{title:title, url:url, hid:hidden},function(res){
            alert ("updated !");
        });
    });
});

注意:我建议您绑定到页面加载时出现的数据div的最近父级而不是绑定到文档