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

时间:2015-02-11 18:42:52

标签: javascript jquery

我知道我可以使用click函数将事件附加到DIV元素,但由于某种原因它不适合我。这是我如何创建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;

}

然后我尝试附加点击事件,如下所示:

   // 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);

但它不起作用且没有附加点击事件。

2 个答案:

答案 0 :(得分:1)

以下是代码

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

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


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

OR

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

答案 1 :(得分:0)

因为你已经在jQuery包装器中创建了div,所以你不需要在$(colorSwatchDiv).click(...再次包装它。另外,您确定colorSwatchDiv变量是引用dom元素而不是内存元素吗?你能在dom的榆树上申请课程吗?

相关问题