Javascript 在使用jQuery添加到列表之前检查div是否存在重复项

Javascript 在使用jQuery添加到列表之前检查div是否存在重复项,javascript,jquery,Javascript,Jquery,这应该是微不足道的,但我有问题 基本上,当用户单击“课程”时,我试图在“所选课程”中添加一个新的“div”。当且仅当当前课程不在“所选课程”框中时,才会发生这种情况 我遇到的问题是,执行此操作时,“selected courses”部分没有附加任何内容。我使用了警报语句来确保代码实际上正在运行。我对道路的理解有什么问题吗?在和上。每项工作?我可以这样用吗 这是一把小提琴 $(文档)。在(“单击”,“div.course”,函数()上){ var title=$(this.find(“span”)

这应该是微不足道的,但我有问题

基本上,当用户单击“课程”时,我试图在“所选课程”中添加一个新的“div”。当且仅当当前课程不在“所选课程”框中时,才会发生这种情况

我遇到的问题是,执行此操作时,“selected courses”部分没有附加任何内容。我使用了警报语句来确保代码实际上正在运行。我对道路的理解有什么问题吗?在和上。每项工作?我可以这样用吗

这是一把小提琴

$(文档)。在(“单击”,“div.course”,函数()上){
var title=$(this.find(“span”).text();
var match_found=0;
//如果列表中没有长度0,则无需检查匹配项
如果($(“.selected course”)。长度>0){
找到匹配项=匹配项(标题);
}
如果(匹配==0){
var out=''+''+'';
$(“#所选框”).append(out);
}       
});
//添加前,检查单击的课程是否已在列表中。
功能匹配(str){
$(“.selected course”)。每个(函数(){
var-retval=0;
如果(str==this.text()){
//已在所选课程部分中的课程
retval=1;
返回false;
}
});
返回返回;
}

尝试此代码,阅读注释了解更改的位置:

$(document).on("click", "div.course", function () {
  var title = $(this).find("span").text().trim(); // use trim to remove first and end whitespace
  var match_found = 0;

  if ($(".selected-course").length > 0) {
    match_found = match(title);
  }
  if (match_found == 0) { // should change into match_found 
    var out = '';
    out += '<div class="selected-course">' + '<a href="#">' + title + '</a>' + '</div>';
    $("#selected-box").append(out);
  }
});

function match(str) {
  var retval = 0; // this variable should place in here
  $(".selected-course").each(function () {

    if (str == $(this).find('a').text().trim()) { // find a tag to catch values, and use $(this) instead of this
        retval = 1;
        return false;
    }
  });
  return retval; // now can return variable, before will return undefined
}
$(文档)。在(“单击”,“div.course”,函数(){
var title=$(this).find(“span”).text().trim();//使用trim删除第一个和最后一个空格
var match_found=0;
如果($(“.selected course”)。长度>0){
找到匹配项=匹配项(标题);
}
如果(match_found==0){//应更改为match_found
var out='';
out+=''+''+'';
$(“#所选框”).append(out);
}
});
功能匹配(str){
var retval=0;//此变量应放在此处
$(“.selected course”)。每个(函数(){
if(str==$(this).find('a').text().trim()){//找到一个标记来捕获值,并使用$(this)代替this
retval=1;
返回false;
}
});
return retval;//现在可以返回变量,以前将返回未定义的
}

更新了

你的小提琴有几个小问题

参见fixed fiddle:

您没有将
这个
包装到jquery对象中。所以它抛出了一个异常,说
这个
没有方法
text()

其次,您的
retval
是在each中声明的,因此无法在each错误的范围外返回

最后,块中的
如果

if (matched== 0) {
    var out = '';
    out += '<div class="selected-course">' + '<a href="#">' + title + '</a>'+'</div>';
    $("#selected-box").append(out); 
}   
if(匹配==0){
var out='';
out+=''+''+'';
$(“#所选框”).append(out);
}   
查看的变量不正确,它正在查看的
匹配的
,该变量不存在,导致异常。

您的问题是:

1.
此.text()
无效。您必须使用
$(this).text()

2.您定义的
var retval=0
每个语句内部
并尝试在
每个语句外部返回它
。因此,将这一行从
每条语句中移出

3.
匹配的
未定义。如果(matched==0){

4.使用
trim()
获取和设置文本,因为文本可能包含前导和尾随空格

你更新的JS是

$(document).on("click", "div.course", function () {
var title = $(this).find("span").text();
var match_found = 0;

if ($(".selected-course").length > 0) {
    match_found = match(title);
}
if (match_found == 0) {
    var out = '<div class="selected-course">' + '<a href="#">' + title + '</a>' + '</div>';
    $("#selected-box").append(out);
}
});

function match(str) {
var retval = 0;
$(".selected-course").each(function () {
    if (str.trim() == $(this).text().trim()) {
        retval = 1;
        return false;
    }
});
return retval;
}
$(文档)。在(“单击”,“div.course”,函数(){
var title=$(this.find(“span”).text();
var match_found=0;
如果($(“.selected course”)。长度>0){
找到匹配项=匹配项(标题);
}
如果(找到匹配项==0){
var out=''+''+'';
$(“#所选框”).append(out);
}
});
功能匹配(str){
var-retval=0;
$(“.selected course”)。每个(函数(){
如果(str.trim()==$(this.text().trim()){
retval=1;
返回false;
}
});
返回返回;
}

依靠检查文本元素所包含的内容并不是解决此类问题的最佳方法。它很容易出错(正如您所发现的那样),速度很慢,代码很长,并且对HTML中的小更改很敏感。我建议改为使用自定义的
数据-*
属性

因此,您将得到如下HTML:

<div class="course" data-course="Kite Flying 101"> 
    <a href="#">
        <span>Kite Flying 101</span> 
    </a>
</div>
$(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);    
    }
});

那么JS将是这样简单的:

<div class="course" data-course="Kite Flying 101"> 
    <a href="#">
        <span>Kite Flying 101</span> 
    </a>
</div>
$(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);    
    }
});
$(文档)。在('click','div.course',function()上{
//获取从属性中单击的课程的名称。
var title=$(this.attr('data-course');
//创建一个选择器,用于选择具有“类选定课程”和“正确的数据课程”属性的所有内容。
变量选择器='。所选课程[数据课程='+标题+'];
if($(选择器).length==0){
//如果选择器没有返回任何内容,请附加div。
//请注意,我们需要在此处添加数据课程属性。
var out='';
$(“#选定框”).append(out);
}
});
不过,请注意课程名称中的大小写敏感性


是一把工作的小提琴。

提供一把小提琴,仅仅通过查看JS,我认为人们无法帮助您解决问题。这是在没有html但查看输出字符串的情况下的推测。您的结构是div中的锚?因此您希望比较锚的文本。但是,您的每个人都在查看div的文本?因此id猜猜在你的每一篇文章中,你想进入锚元素,然后得到文本?忽略这一点,用小提琴测试就可以了。但是你没有得到一个例外吗?我必须将它包装在jquery对象中才能使它工作。很好地展示了一种“更好”的方法来完成它。因此,这些答案似乎很奇怪,有些人认为不做你不做的事情直接回答问题,而其他人对此表示赞同。谢谢您的回答!