如果类存在,如何将值放入数组中
我有一个div里面有一个class =“price”的值列表,如果class存在,否则/不存在。
div模式是.mainDiv> span,.price有时候模式将是.mainDiv>跨度有时.mainDiv> .price
所以如果class =“price”存在,如何将价格值推入数组中。
下面是DOM树。
<div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$2000</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$300</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <!-- observe here price is not there --> </div>
我正在使用这样的代码
var arr = []; $('.mainDiv').each(function(i){ if ($(this).hasClass('price')){ arr.splice(i, 0, $(this).text()); } else { arr.splice(i, 0, 'no price'); } });
请提前帮助我
首先,当.price
元素是一个孩子时,你在.mainDiv
本身上使用hasClass()
。 您可以使用has()
或find().length
来获取元素。
你也可以使用map()
来创build你的数组。 尝试这个:
var arr = $('.mainDiv').map(function() { return $(this).has('.price') ? $(this).text() : 'no price'; }).get();
您的代码中存在各种问题
-
$(this).hasClass('price')
– 这里的hasClass()
方法的工作方式并不像你hasClass()
那样has()
方法。 它是检查所选元素的类而不是它的下降。 所以使用$(this).has('.price').length
来代替 -
$(this).text()
– 回顾所有div文本,因为您只需要使用$('.price', this).text()
来代替价格。
在jQuery中使用map()
方法进行优化。
// iterate aver all div var arr = $('.mainDiv').map(function(i) { // cache the `.price` element var $price = $('.price', this); // check `.price` element present or not // and based on that generate the element return $price.length ? $price.text() : 'no price'; // get the array from the generated jQuery object }).get(); console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$2000</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <div class="price">$300</div> </div> <div class="mainDiv"> <span>abcdsnndsjdjnd</span> <!-- observe here price is not there --> </div>