将事件附加到动态创建的 dom 元素

Attach event to a dynamically created dom element

在下面的代码中,我动态创建了不同的 post。 每个 post 都有自己的图像。

$(function () {
    for(post in data){
        //get from the data post details

        var titleData = data[post]["title"];
        var descriptionData = data[post]["description"];
        var imageData = "images/"+data[post]["image"];
        //create elements with jquery
        var postHolder = $('<div class="post row"></div>');
        var img = $('<img src="'+imageData+'" data-title="'+titleData+'" class="col-sm-3 img-post">');
        var textHolder = $('<div class="col-sm-9"></div>');
        var title = $('<h4 class="title-post"></h4>').append(titleData);
        var description = $('<p class="explanation-post"></p>').append(descriptionData);

        
        textHolder.append(title);
        textHolder.append(description);

        postHolder.append(img);
        postHolder.append(textHolder);
        $('.posts-container').append(postHolder);


        img.on('click',function(){alert(this.data-title);});

    }


});

我希望当我点击图片时,它会提示 post 的标题(所谓的“titleData”)并且“textHolder”会将其背景颜色更改为灰色。

此挑战的限制是:

  1. 每次传递不同的参数作为“titleData”。
  2. 要使用内存中的最小 space。

警报中的内容有误。

你说的是

this.data MINUS title

如果名称中有破折号,您应该使用方括号表示法。

alert(this["data-title"]);

或更好地使用 getAttribute

alert(this.getAttribute("data-title"));

或jQuery

alert($(this).data("title"));
alert($(this).attr("data-title"));

所以 bg 颜色变化的最终代码应该是

img.on('click', function() {
    alert($(this).attr("data-title"));
    textHolder.css("background-color","#CCC");
    console.log(textHolder.css("background-color"))
});

data-title 是 JavaScript 中的无效标识符。要访问 data-* 属性,您可以使用 HTMLElement.dataset

 alert(this.dataset.title)

或者,因为您正在使用 jQuery .data() 方法。

alert($(this).data("title"));