javascript
  • jquery
  • html
  • 2017-06-29 39 views 2 likes 
    2

    我有这样的功能:如何将点击事件添加到我在JavaScript中构建的按钮中?

    var ButtonChoice = function(key, type, img, label){ 
    this.key = key; 
    this.type = type; 
    this.img = img; 
    this.label = label; 
    this.getButton = function(){ 
    return "<img src='img/" + this.img + "' type='" + this.type + "' id='" + 
         this.key + "' class='ButtonsChoice' description='" + this.label + 
         "' />" 
    }; 
    }; 
    

    ,我需要点击功能添加到该图像。我的问题是如何做到这一点?

    +0

    首先将它添加到DOM,然后引用'Element',您可以调用'element.addEventListener('click',function(){// do something});' – Yoda

    +1

    [Event binding在动态创建的元素?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Liam

    回答

    -1

    此事件侦听器添加到document.ready()事件侦听器:

    $('.ButtonsChoice').click(function(e){ 
        ... do something ... 
    }); 
    

    当然,这把所有的按钮,有一个班的同...

    +0

    这可能无法正常工作。 'ButtonChoice'是一个函数*,这意味着它将在文档准备就绪后调用。所以你需要事件委派。 –

    +0

    这不会工作,因为按钮是动态创建的,您需要使用和事件代理 – Liam

    0

    只需添加的onclick功能,以您的返回值:

    return "<img src='img/" + this.img + "' type='" + this.type + "' id='" + 
         this.key + "' class='ButtonsChoice' description='" + this.label + 
         "' onclick='yourFunc();' />" 
    
    +0

    虽然这可行,但它是非常古老的学校,并且通常建议您不要使用'onclick =' –

    -1

    你能做到这样,

    <img src="example.gif" onclick="a('hello')"> 
    
    在img标签内的上述行

    添加一个onclick事件将调用一个函数一(值)

    +0

    * sigh *每个人都可以请阅读该死的问题.... – Liam

    2

    不是作为一个HTML字符串创建图像的你可以创建它使用JavaScript动态,这将允许您使用onclick动态附加click事件。

    这是应该的代码:

    var ButtonChoice = function(key, type, img, label) { 
        this.key = key; 
        this.type = type; 
        this.img = img; 
        this.label = label; 
        this.getButton = function() { 
        var image = document.createElement("img"); 
        image.src = "img/" + this.img; 
        image.type = this.type; 
        image.id = this.key; 
        image.className = "ButtonsChoice"; 
        image.description = this.label; 
        image.onclick = function(){ 
         //Put your code here 
        } 
        return image; 
        }; 
    }; 
    

    注:

    我不明白你为什么要使用你的图像type属性,type属性通常与投入使用和按钮,请查看MDN HTML attribute reference表以了解更多详情。

    +1

    感谢上帝给出了一个明智的答案.... – Liam

    +0

    Hhhhh @Liam是这是最基本和合理的方式来做到这一点。 –

    相关问题