Javascript 使用jquery查找具有特定id值的子元素

Javascript 使用jquery查找具有特定id值的子元素,javascript,jquery,parent-child,Javascript,Jquery,Parent Child,我想知道,是否有一个子div具有当前单击div的id属性 $(document).on('click', '.sw-item' , function() { if ($("#softwarelist").find("div").attr('id', '' + $(this).attr("id") + '').length = 0) { $("#softwarelist").append("<div id='" + $(this).attr("id") + "' cl

我想知道,是否有一个子div具有当前单击div的id属性

$(document).on('click', '.sw-item' , function() {
    if ($("#softwarelist").find("div").attr('id', '' + $(this).attr("id") + '').length = 0) {
        $("#softwarelist").append("<div id='" + $(this).attr("id") + "' class='softwarelist-item'>" + $(this).html() + "</div>");
    }
});
$(文档).on('click','sw item',function(){
if($(“#软件列表”).find(“div”).attr('id'),'+$(this.attr(“id”)+'.length=0){
$(“#软件列表”).append(“+$(this.html()+”);
}
});

当我在#softwarelist中发现一个子div时,我不想将其追加(添加)到softwarelist div中。append可以工作,但if语句是错误的。有人知道正确的if语句吗?

按照您的方式,您正在设置
id
。为
.attr()
提供第二个参数将被设置,而不是get

if ($("#softwarelist").find("div").attr('id') == '' + $(this).attr("id") + '') {

您可以获取要查找的id,然后将其转换为选择器,然后使用
.find()
查看是否在
#softwarelist
中找到该选择器:

$(document).on('click', '.sw-item' , function() {
    if ($("#softwarelist").find("#id" + this.id).length) {
       // child id found
    }
});
解决方案

$(document).on('click', '.sw-item' , function() {
    if ($("#softwarelist").find("div[id = '" + $(this).attr("id") + "']").length == 0) {
        $("#softwarelist").append("<div id='" + $(this).attr("id") + "' class='softwarelist-item'>" + $(this).html() + "</div>");
    }
});
$(文档).on('click','sw item',function(){
if($(“#软件列表”).find(“div[id=”+$(this.attr(“id”)+”])。length==0){
$(“#软件列表”).append(“+$(this.html()+”);
}
});

用户Itay Gal已经指出id应该是唯一的

我想我现在明白你的要求了。 如果用户单击某个产品,则应仅将该产品添加到
软件列表中一次。
因此,您希望测试此特定产品是否已在列表中,并仅在尚未添加时添加它

带有产品列表的HTML
通过这种方式,您可以测试产品是否已经在softwarelist中,而无需通过两次使用id创建无效html。

id应该是唯一的,因此,您无需努力查找它,只需使用
$(“#id”)
就可以搜索与另一个元素具有相同id的元素了?这就是您的问题所在。在另一个div中使用相同的id。更改了运算符==并且现在它在第一次单击时追加ony。(this)元素是与#softwarelist相同的另一个div。在另一个div中不能有相同的ID,ID对于整个documentyway都是唯一的,这样就可以了->
$(“#softwarelist[ID=”+this.ID+“]”)这是有效的,但只对我单击的第一个元素有效。当我单击第二个div时,我可以将div追加到多个div。因此,我需要给attr id赋值$(this).attr(“id”)-因为这是单击元素的id。当它找到id值为的div时,我不想将id相同的div添加到#softwarelist。
<div id="softwareItems">
<div id="p7" class="sw-item">Windows 7</div>
<div id="p2013" class="sw-item">Visual Studio 2013</div>
<div id="p00" class="sw-item">Beyond Compare</div>
</div>
<div id="softwarelist">
     <h3>You picked these items</h3>
</div>  
$(document).on('click', '.sw-item' , function() {               
    var thisID = $(this).attr("id");
    var softwareList = $("#softwarelist");
    var elementsFound = softwareList.find("div[data-product='"+thisID +"']");

    if (elementsFound.length == 0) {
         softwareList.append("<div data-product='" +thisID + "'>"  
                                 + $(this).html()  
                           + "</div>");
    }    
});