简体   繁体   English

使用选择器的jquery的if else语句,以查看是否已将某个div附加到该语句

[英]If else statement for jquery using selectors to see if a certain div has been appended to it

Would this work if you had a div and you append one of these div to ? 如果您有一个div并将这些div之一附加到该列表上,该方法是否可行? Such as

<div class ="append">
  <div id ="one"></div>
  <div id ="two"></div>
</div>

Then in jQuery do something like: 然后在jQuery执行以下操作:

if ($(.append#one)) {do this}
else if ($(.append#two)){do this} 

each of the div #one and #two have different numbers and that matters. 每个div #one#two具有不同的数字,这很重要。 So I was wondering if you could somehow do an if statement to check if a div has a another div with an id appended in it, if so you do the code else if its another div with another id do code. 所以我想知道您是否可以以某种方式执行if语句来检查div是否具有附加了id的另一个div,如果是的话,则执行代码,否则如果它的具有另一个id的另一个div进行了代码。

Edit: The divs with the id one and two are not appended to div with class append at first, i have to pick either one or two to get appended to the div append. 编辑:ID为1和2的div不会首先附加到具有class append的div上,我必须选择一个或两个才能附加到div附加上。 So can i check if the div .append has either div#one appended to it, if so do this, else if div#two appended to it do this 所以我可以检查div .append是否附加了div#one,如果这样做,否则是否附加了div#two

check if a div has a another div with an id appended in it 检查一个div是否有另一个div附加了id

You can use: 您可以使用:

if ($(".append>[id]").length > 0)

or 要么

if ($("div>div[id]").length > 0)

which will check return all items that are direct descendants of .append and have attribute id . 它将检查是否返回.append直接后代并具有id属性的所有项目。

You can do it like following. 您可以按照以下步骤进行操作。

if ($('.append #one').length) {
   // do this
}
else if ($('.append #two').length) {
   // do this
} 

You could check if a div has a particular parent as well 您可以检查div是否也有特定的父项

if($( "#one" ).hasClass( "append" )){
  //do something
}else if($( "#two" ).hasClass( "append" )){
  //do something
}

 $(()=>{ $('#div-one').click(()=>{ $('#one').appendTo($('.append')); }); $('#check').click(()=>{ if($('.append').children('#one').length!=0){ alert('one'); } else{ alert('two'); } }); }); 
 .append{color:Red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class = "append">append</div> <div id ="one">one</div> <div id ="two">two</div> <br/> <input type='button' id='div-one' value ='append one'/> <input type='button' id='check' value='check'/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM