检查列表是否具有相同ID的元素

时间:2014-09-16 07:03:16

标签: jquery

我有以下HTML代码。

<div class="list">
   <p id="item1">Item 1</p>
   <p id="item2">Item 2</p>
   <p id="item3">Item 3</p>
   <p id="item4">Item 4</p>
</div>

<input name="item1" type="checkbox"/>
<input name="item6" type="checkbox"/>
<input name="item5" type="checkbox"/>

当我点击复选框时,我想向<p>添加新的<div>标记,其中id就像输入name一样。

$('input').click(function(){
   $('.list').append('<p id="' + $(this).attr("name") + '"</p>'); 
});

但不应重复具有相同ID的项目!我怎么检查它? 我想我需要遍历我的<p>这样的列表

$('.list p').each(function(){
    if (..element with same id exists..) {
        ....    
    } else {
       ('.list').append('<p id="' + $(this).attr("id") + '"</p>');    
    }
});

4 个答案:

答案 0 :(得分:0)

你可以使用.list中的段落元素的长度,并在最后使用id变量来使它们成为唯一:

$('input').click(function(){ 
  if($(this).is(':checked')){// on checked true
  var p_length=$('.list p').length; //find length of p elements
  if(p_length==0)
    $('.list').append('<p id="' + $(this).attr("id") + '"</p>');    
  else
    $('.list').append('<p id="' + $(this).attr("name")+"_"+p_length + '"</p>'); 
 }
});

答案 1 :(得分:0)

您可以通过ID:

选择所选对象的长度道具
$("#YourId").length >0 //this means id already exist.

这里是ref链接:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-‌​exists/

jquery how to find if div with specific id exists

答案 2 :(得分:0)

试试这个$(element).has('#id');

   if( $('.list').has('#foo') )
{
  //dont append
}
else
{
//append
}

答案 3 :(得分:0)

试试这个:

$('input').on('click', function(){
    inputId = $(this).attr('name');
    console.log($('.list').find('#' + inputId));
    if($('.list').find('#' + inputId).length === 0)
    {
        $('.list').append('<p id="' + inputId + '"></p>'); 
    }
});

DEMO