我通过在jQuery中执行以下操作,在点击时为标签添加标签
$('.addTag').live('click', function () {
$('.pendingTags').html($('.pendingTags').html() + $('.newTag').val() + ', ');
});
但我需要做的是查看$('.newTag').val()
.pendingTags
知道我怎么能做到这一点吗?
由于
答案 0 :(得分:1)
使用.text()
方法,而不是.html()
方法。此外,您应该在新标记之前添加逗号。
$('.addTag').live('click', function () {
var currentTags = $('.pendingTags').text(); // Get current labels
var newTag = $('.newTag').val(); // Get new label
var listOfTags = currentTags.split(','); // Create list of labels
for(var i=0, l=listOfTags.length; i<l; i++) {// Loop through each
if(listOfTags[i] == newTag) return; // If the label exists, return
}
var sep = /^\s+$/.test(currentTags) ? "" : ","; // Create separator
$('.pendingTags').text(currentTags + sep + newTag); //Not returned, add label
});
答案 1 :(得分:0)
$('.addTag').live('click', function () {
if(!containsTag($('.pendingTags').html())
$('.pendingTags').html($('.pendingTags').html() + $('.newTag').val() + ', ');
else
alert('you have it already');
});
function containsTag(val, tag)
{
var tags = val.split(',')
for(var i = 0; i < tags.length; i++)
{
if($.trim(tags[$i]).toLowerCase() == tag.toLowerCase())
return true;
}
return false;
}
我创建了一个方法,用于检查标记列表中是否存在标记,不区分大小写。
答案 2 :(得分:0)
您可以使用jQuery.fn.filter()
根据回调过滤jQuery对象:
$('.pendingTags')
//before adding the html, we filter the jquery set
.filter(function(){
return $(this).text().split(', ').indexOf($('.newTag').val()) < 0;
})
//and only add the html to the new set
.html($('.pendingTags').html() + $('.newTag').val() + ', ');
答案 3 :(得分:0)
备用解决方案(working example):
$('.addTag').live('click', function () {
var pending = $('.pendingTags').html();
var newTag = $('.newTag').val();
if((', ' + pending).indexOf(', ' + newTag + ', ') < 0) {
$('.pendingTags').html(pending + newTag + ', ');
}
});