简体   繁体   English

使用jQuery库将Click事件附加到DIV

[英]Attaching Click Event to DIV Using jQuery Library

I am aware I can use the click function to attach an event to the DIV element but for some reason it is not working for me. 我知道我可以使用click函数将事件附加到DIV元素,但由于某种原因,它对我不起作用。 Here is how I am creating the DIV element. 这就是我创建DIV元素的方式。

function createColorSwatchDiv(color) {

    var colorSwatchDiv = $("<div>");

    var image = $("<img>");
    image.attr("src",color.imageURL);

    var label = $("<label>");
    label.text(color.title);

    colorSwatchDiv.append(image);

    return colorSwatchDiv;

}

Then I try to attach the click event like the following: 然后,我尝试附加如下所示的click事件:

   // run a loop and build the grid layout
    for(index = 0; index < colors.length; index++) {

        var colorSwatchDiv = createColorSwatchDiv(colors[index]);

        // attach the event
        colorSwatchDiv.click(function(){

                alert('hello world');

        });

        colorsSection.append(colorSwatchDiv);

    }

    // add to the dom
    $("#color .imageChartOption").after(colorsSection);

But it does not work and no click event is been attached. 但是它不起作用,并且没有附加单击事件。

following is the code 以下是代码

 var $newdiv1 = $("<div id='object1' onClick=Test()>Hello</div>");

 $("body").append($newdiv1);


function Test()
{
    alert("Clicked");
}

OR 要么

  $newdiv1.on('click',function(){alert("hello");});

由于您已经在jQuery包装器中创建了div,因此无需在这里再次包装$(colorSwatchDiv).click(... 。此外,您确定colorSwatchDiv变量引用的是dom元素,而不是内存中的对象。您可以在dom的榆树上上课吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM