簡體   English   中英

如果存在類,如何將值放入數組

[英]how to to put values into array if class is present

我在div內有一個值列表,如果有class,則iam會被iam插入以將值推入數組/否則“不存在”。

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');
    }
});

請事先幫助我

您的代碼中存在各種問題

  1. $(this).hasClass('price') -這里的hasClass()方法的工作與您期望的不像has()方法。 它檢查所選元素的類而不是其下降體。 因此使用$(this).has('.price').length代替
  2. $(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> 

首先,當.price元素是子元素時,您在.mainDiv本身上使用hasClass() 您可以使用has()find().length來獲取元素。

您還可以通過使用map()創建數組來簡化此過程。 嘗試這個:

var arr = $('.mainDiv').map(function() {
    return $(this).has('.price') ? $(this).text() : 'no price';
}).get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM