[英]How the heck do I do string comparison from a list item to the items in an array
我試圖在一個 UL 中獲取單個列表項的內容,當單擊一個時,將該單個 LI 的值添加到數組中,並將列表項的文本字符串附加到頁面上其他位置的有序列表項。
我在比較單擊的 LI 的字符串時遇到問題,遍歷數組以確保 LI 的字符串列出一次,然后將文本添加到 OL。 幫助表示贊賞。
var list = $('.list'),
listItem = $('.list li'),
container = $('.list-content ul'),
containerItem = $('.list-items li');
itemArray = [];
listItem.on({
'click' : function(){
var current = $(this),
currentText = $(this).text();
if( itemArray.length <= 0 ) {
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
}else{
for( var count = 0; count < itemArray.length; count++){
if( currentText === itemArray[count] ){
return false;
break;
} else {
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
break;
}
}
}
}//end of click function
});
您可以使用$.inArray()檢查對象是否存在於數組中
這應該做
var list = $('.list'),
listItem = $('.list li'),
container = $('.list-content ul'),
containerItem = $('.list-items li'),
itemArray = [];
listItem.on({
'click' : function(){
var current = $(this),
currentText = $(this).text();
if($.inArray(currentText, itemArray) == -1){
itemArray.push(currentText);
$('<li>'+ currentText + '</li>').appendTo(container); //add text to new area
}
}//end of click function
});
演示:小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.