我有一个jquery进行ajax调用并使用class = criteria-selctor构建<li tags>
列表。
我有另一个jquery,它会在点击属于class = criteria-selector。
的元素时触发我面临的问题是jquery触发器不适用于由javascript构建的li元素..
请帮忙.. !!! 感谢。
以下是代码:
var callCollectionsAPI = function() {
$.ajax({
url: {{settings.api_base_url}} + '/collections',
method: 'GET',
success: function(collections) {
renderCollectionsResult(collections);
}
});
}
var renderCollectionsResult = function(collections) {
var subjectsElement = document.getElementById("subjects");
var stylesElement = document.getElementById("styles");
var subjectsInnerHTML = '', stylesInnerHTML = '';
var subjectsCollection = collections['subjects'];
var stylesCollection = collections['styles'];
for (var i=0; i<subjectsCollection.length; i++) {
subjectsInnerHTML = subjectsInnerHTML + getCollectionsHTML(subjectsCollection[i]);
}
for (var i=0; i<stylesCollection.length; i++) {
stylesInnerHTML = stylesInnerHTML + getCollectionsHTML(stylesCollection[i]);
}
subjectsElement.innerHTML = subjectsInnerHTML;
stylesElement.innerHTML = stylesInnerHTML;
}
var getCollectionsHTML = function(collections) {
var listHtml = '<li> <a href="#" id="'+ collections['title'] +'" data-value="' + collections['title'] + '" class="criteria-selector">' + collections['title'] + '(78) </a> </li>'
return listHtml;
}
上面的代码基于ajax调用构建dom ..! 下面的代码需要选择所有带有类的元素 - &#39; criteria-selector&#39;但它不适用于上述代码构建的代码,适用于加载前编写的html。
var classHighlight = 'highlight';
var $thumbs = $('.criteria-selector').click(function(e) {
e.preventDefault();
var target = $(this);
var listNode = $(target.parents('ul')[0]).find('.highlight').removeClass(classHighlight);
$(this).addClass(classHighlight);
var id = this.id;
var priceBucketRange='&priceBucketRange=' + id;
$.ajax({
url: 'http://localhost:8080/api/artworks/search/?page=0' + priceBucketRange,
method: 'GET',
success: function(artworks) {
renderResult(artworks);
}
});
});
答案 0 :(得分:1)
您最有可能使用直接事件处理程序。在这种情况下,您应该在构建新DOM之后再次绑定事件处理程序,或者您应该切换到委托的那些:
// direct
$.ajax({
success: function (data) {
// build DOM
$(".criteria-selector").bind("click", function (event) {
// bind events on new dom
});
}
});
// delegated
$(document).on("click", ".criteria-selector", function (event) {
// bind delegated event handler on the document and fire the event
// for every element matching the criteria selector, regardless of
// when this element was created
});