捕获指定元素的负载

catch load of a specified element

本文关键字:负载 元素      更新时间:2023-09-26

我想捕获/处理指定项目的负载(如果它是动态加载的(。

如果事件click则工作正常:

$('#articles').on("click",".article",function(eo){
        //...               
    });

这是我尝试过的:

$(document).on("load","input",function(){
    alert(1);
});​

这就是我将如何使用它:

<input type=hidden name='size' value=1>
<select name='size'>
  <option value=0>A4</option>
  <option value=1>A3</option><!--this will be selected, that is indicated with the hidden input-->
</select>

执行此操作的脚本:

$(document).on("load","input",function(e){
    var name = e.attr("name");
    var val = e.val(); 
    if(name!=""&& typeof(e)!="undefined")
    {
       e.parent().find('select[name='+name+']').val(val);               
    }       
});​

如果可能的话,我问某种 on(( 函数,因为手册说它是首选。

我建议如下:

$(document).on('DOMNodeInserted', 'input', function(e) {
    console.log($(this));
});

JS小提琴演示。

如果您担心那些使用未实现DomNodeInserted的浏览器的体验,那么您当然可以在元素附加到 DOM 的点触发具有自定义事件名称的事件,然后使用 on() 方法侦听事件:

$(document).on('customEventName', 'input', function(e) {
    console.log($(this));
});
$('#add').click(
    function() {
        var i = $('input').length,
            input = $('<input />',{'id' : 'input_' + i});
        input.appendTo('body').trigger('customEventName');
    });​

JS小提琴演示。

<小时 />

引用:

  • DOM 级别 3 事件,包括 DOMNodeInserted .
  • on() .
  • trigger() .

你可能想看看 jquery 的 livequery 插件:

http://docs.jquery.com/Plugins/livequery

$('input') 
.livequery(function(){ 
alert(1);
}

如果它是动态加载的元素,请尝试.live(),其工作原理类似于.bind()仅保持动态添加元素的搜索打开并在它们出现时绑定它们。

如果要查找特定元素,则可以使用 setTimeout 定期查找与新选择器匹配的元素。

function findNew() {
   var $selected = $('.some-selector').filter(function() {
       return !$(this).data('filtered');
   });
   $(document).trigger({type: 'elementadded', elements:$selected });
   $selected.data('filtered', true);
   setTimeout(findNew, 500);
}
$(document).on('elementadded', function(e) {
  alert('found ' + e.elements.length + ' new elements.');
});
findNew();