这应该是微不足道的,但我遇到了问题...
基本上,我想做的是当用户单击“课程”时将新的“ div”添加到“所选课程”。仅当当前课程尚未在“所选课程”框中时,才应该发生这种情况。
我遇到的问题是执行此操作时,“选择的课程”部分没有任何内容。我已使用警报语句来确保代码实际上正在运行。我对.on和。每种工作方式的理解有什么问题吗?我可以这样使用它们吗
这是一个小提琴http://jsfiddle.net/jq9dth4j/
$(document).on("click", "div.course", function() {
var title = $( this ).find("span").text();
var match_found = 0;
//if length 0 nothing in list, no need to check for a match
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (matched == 0) {
var out = '<div class="selected-course">' + '<a href="#">' + title + '</a>'+'</div>';
$("#selected-box").append(out);
}
});
//checks to see if clicked course is already in list before adding.
function match(str) {
$(".selected-course").each(function() {
var retval = 0;
if(str == this.text()) {
//course already in selected-course section
retval = 1;
return false;
}
});
return retval;
}
依靠检查文本元素包含的内容并不是解决此类问题的最佳方法。它很容易出错(如您所知),它可能很慢,给您的代码很长,并且对HTML中的细微变化很敏感。我建议改用自定义data-*
属性。
因此,您将获得如下所示的HTML:
<div class="course" data-course="Kite Flying 101">
<a href="#">
<span>Kite Flying 101</span>
</a>
</div>
然后,JS会像这样简单:
$(document).on('click', 'div.course', function() {
// Get the name of the course that was clicked from the attribute.
var title = $(this).attr('data-course');
// Create a selector that selects everything with class selected-course and the right data-course attribute.
var selector = '.selected-course[data-course="' + title + '"]';
if($(selector).length == 0) {
// If the selector didn't return anything, append the div.
// Do note that we need to add the data-course attribute here.
var out = '<div class="selected-course" data-course="' + title + '"><a href="#">' + title + '</a></div>';
$('#selected-box').append(out);
}
});
但是,请注意课程名称中的区分大小写!
这是一个工作的小提琴。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句