我正在尝试在每一行上添加点击事件。点击后我需要能够获取名称(例如Jeremy)并放在顶部div中,替换问号。我的点击事件仅适用于id =“data”,但不适用于子div。我在codepen上也有我的代码http://codepen.io/rrschweitzer/pen/GrRyLg?editors=0110。非常感谢任何帮助!!
这是我的HTML:
MyEntity(ndb.Model):
a_key = ndb.KeyProperty()
entities = MyEntity.query(MyEntity.a_key == some_key)
这是我的Jquery:
<div id="interview-test">
<div class="top-bars">
<div id="secret">???</div>
<button id="clear">Clear</button>
</div>
<div id="data"></div>
</div>
答案 0 :(得分:0)
您需要在创建元素(行)后添加事件侦听器:
(function($) {
$.fn.interviewTest = function() {
var self = this;
var testData = null;
var url = "https://private-f3b4b-interview2.apiary-mock.com/data";
// create rows
self.createRow = function(data) {
var theRow = $('<div>').addClass('rows')
.append($('<div>').addClass('image-container')
.append($('<img>').addClass('picture').attr('src', data.image)))
.append($('<div>').addClass('name').append($('<h1>').html(data.name)))
.append(self.getDate(data.timestamp))
return theRow;
}
self.getDate = function(date) {
var date = date.slice(0,-3)
var newdate = new Date(date * 1000)
var year = newdate.getFullYear();
var month = newdate.getMonth();
var day = newdate.getDay()
var formattedDate = month + '/' + day + '/' + year
return formattedDate;
}
// api call
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ');
},
url: url,
success: function(data, status) {
var dataObject = data;
var i = 0;
var testData = [];
for(var key in dataObject) {
testData[i] = dataObject[key]
i++;
}
// console.log(testData);
self.createDataList(testData, i);
}
})
self.createDataList = function(data, size) {
var rows = $(self).find('#data');
if (size != 0) {
$.each(data, function(key, value) {
// console.log(value)
rows.append(self.createRow(value))
});
self.addEventListeners()
}
}
self.addEventListeners() {
// event listeners
$(self).find('.rows').on('click', function(e) {
var current = $(e.currentTarget);
console.log(current);
// if(current)
})
}
}}(jQuery))$('#interview-test').interviewTest();
答案 1 :(得分:0)
您可以使用事件委托将事件附加到父元素,该元素将为所有匹配的选择器子元素触发。
$(self).on('click', ".rows",function(e) {
var current = $(this);
if(current)
{
var name = current.find(".name").text();
$("#secret").text(name);
}
})
答案 2 :(得分:0)
您的演示无法正常工作,但在ajax完成并创建行之前,您正在尝试查找代码self.find('.rows')
您需要委派事件或等到在ajax成功中添加行