代码之家  ›  专栏  ›  技术社区  ›  ncubica

Javascript原型最佳实践事件处理程序

  •  3
  • ncubica  · 技术社区  · 14 年前

    var template = new Template("<li id='list#{id}'>#{value}</li>");
    var arrayTemplate = [];
    arrayOfItem.each(function(item, index){
       arrayTemplate.push(template.evaluate( id : index, value : item))
    });
    

    在这两个选项之后,通过“更新”或“插入”添加列表

    ----- $("elementToUpdate").update("<ul>" + arrayTemplate.join("") + "</ul">);

    问题是

    如何添加事件处理程序而不重复读取数组的过程,这是因为如果在更新或插入之前尝试添加事件,则会出现错误,因为元素不在DOM上。

    所以我现在要做的是在插入或更新之后:

    arrayOfItem.each(function(item, index){
       $("list" + index).observe("click", function(){
         alert("I see the world");
       })
    });
    

    2 回复  |  直到 13 年前
        1
  •  1
  •   edwin    14 年前

    $("list" + index) .

    我会考虑两种方法:

    1) 让click事件在$(“elementToUpdate”)中出现:

    $("elementToUpdate").observe("click", function(evt){
         alert("I see the world");
    });
    

    您可以在evt对象中找到单击的li。

    2) 不要重复做 $(“列表”+索引) ,但只是

    $("elementToUpdate").find("li").each(...);
    

    (假设您使用的是jQuery。原型也有相似之处)。

        2
  •  0
  •   ncubica    14 年前

    你好, 如果你真的想看每个人 li 除非有很好的理由这样做,否则我不会使用 每个处理器上的处理程序 ; 我会在elementToUpdate(或 ul 在它里面)而不是只有一个处理程序:

        $("elementToUpdate").observe("click", function(event) { 
            var li; 
            // Find out which `li` was clicked: 
            li = event.findElement("li"); 
            if (li) { 
                // Do something with the `li` 
            } 
        }); 
    Prototype 1.7 has a new feature to simplify that a bit: 
        $("elementToUpdate").on("click", "li", function(event, li) { 
            // Do something with the `li`;  note it's given as the second 
            // argument to the function 
        }); 
    

    …在幕后,原型基本上就是我做的 上面。如果您仍在使用1.6(以及 因为1.7仍然是RC1,我想你可能是)。

    嗯,

    T.J.克劳德 独立软件顾问 tj/crowder软件/com www.crowdersoftware.com

    http://groups.google.com/group/prototype-scriptaculous/browse_thread/thread/fec98641d72f6fea#