簡體   English   中英

使用jQuery庫將Click事件附加到DIV

[英]Attaching Click Event to DIV Using jQuery Library

我知道我可以使用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;

}

然后,我嘗試附加如下所示的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);

但是它不起作用,並且沒有附加單擊事件。

以下是代碼

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

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


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

要么

  $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