zoukankan      html  css  js  c++  java
  • 为动态生成的html元素增加事件处理

    Adding OnClick property to dynamicly genertated html element


    function klik(){
    alert("ppp");
    }

    function addNewImg(newImageId){
    newImg = document.createelement('img');
    newImg.id = "image"+newImageId;
    newImg = document.getElementById("divimage1").appendChild(newImg);
    newImg.onclick=klik
    }

    it works. The new image is created and after clicking on it "ppp" is alerted.

    but when I use this:

    function klik(ff){
    alert(ff);
    }

    function addNewImg(newImageId){
    newImg = document.createelement('img');
    newImg.id = "image"+newImageId;
    newImg = document.getElementById("divimage1").appendChild(newImg);
    newImg.onclick=klik("ppp");
    }

    "ppp" is alerted in the moment of executing the statement newImg.onclick=klik("ppp"); and when clicking on the generated image nothing happens, even Javascript Console of Firefox stays blind.



    function addNewImg(newImageId){
    newImg = document.createelement('img');
    newImg.id = "image"+newImageId;
    newImg = document.getElementById("divimage1").appendChild(newImg);
    var onC='ppEdit("image'+newImageId+'","image")';
    document.getElementById("image"+newImageId).onclick=new Function(onC);
    }

    it works

    maybe an object detection be great to add too
    why?
    So browsers that understand document.getElementById,
    document.createelement execute the code.


    function addNewImg(newImageId){
    //object detection check
    if (!document.getElementById &&!document.createelement){return;}
    newImg = document.createelement('img');
    newImg.id = "image"+newImageId;
    newImg = document.getElementById("divimage1").appendChild(newImg);
    var onC='ppEdit("image'+newImageId+'","image")';
    document.getElementById("image"+newImageId).onclick=new Function(onC);
    }

    alternative solution:
    if (!document.getElementById) {return;}
    document.getElementById("image"+newImageId).onclick=function(){
    ppEdit(this.id, "image");
    }

  • 相关阅读:
    Django 2.1 配sql server 2008R2
    1.内网安全代理技术
    3.frp搭建socks5代理
    2.变量常量和注释
    1.域环境&工作组&局域网探针方案
    4.nps搭建socks5代理
    1.php介绍和安装
    2.内网安全隧道技术
    3.横向smb&wmi明文或hash传递
    5.域横向CobaltStrike&SPN&RDP
  • 原文地址:https://www.cnblogs.com/goody9807/p/960396.html
Copyright © 2011-2022 走看看