簡體   English   中英

檢查元素是否沒有屬性jQuery

[英]Check if element doesn't have attribute jQuery

onClick一項它添加一個屬性。 只能選擇三個項目,因此頁面上只有三個元素,其屬性如下: data-selected: 1data-selected: 2data-selected: 3

if ($('.item').attr('data-selected', '1') || $('.item').attr('data-selected', '1') || 
    $('.item').attr('data-selected', '1')) {
}

我可以做一個if語句來檢查一個元素是否有一個attribute ,如何檢查所有帶有.item類的元素.item都有一個屬性,如果沒有,那么就做一些事情。

在處理數據屬性時使用data()方法而不是attr() ,現在你必須在數據屬性設置器和getter之間有所區別。

塞特:

$('.item').data('selected', '1'); // assign to the data attribute selected the value 1

吸氣:

$('.item').data('selected'); //get the value 1 from data attribute selected

嘗試存儲在變量中selected的數據屬性的值,然后檢查:

var selected = $('.item').data('selected');

if (selected == 1 || selected ==2 || selected == 3) {
    //Code here
}

如何檢查.item類的所有元素是否具有屬性,如果沒有,則執行某些操作。

您可以使用Jquery而不是selector :not()將選擇與給定選擇器不匹配的所有元素。

if($('.item:not([data-selected])').length)
    //Not all items has attribute data-selected
else
    //All items has attribute data-selected

希望這可以幫助。

只需檢查所選元素是否具有必需屬性(或不具有)。 您可以.filter或使用.not 穿越功能。

**更新**

根據我對此問題的理解,您希望將選擇限制為僅三個項目。 這是一個提案:

 $(function () { $('.item').on('click', function () { var checked = $(this).prop('checked'); // currently checked? var selected = $('.item').filter('[data-selected]'); if (checked) { $(this).attr('data-selected', -1).parent().addClass('selected'); selected = selected.add(this); } else { $(this).removeAttr('data-selected').parent().removeClass('selected'); selected = selected.not(this); } selected.sort(function (a, b) { return $(a).attr('data-selected') - $(b).attr('data-selected'); }).each(function (index) { if (index >= 3) { $(this).prop('checked', false).removeAttr('data-selected').parent().removeClass('selected'); } else { $(this).attr('data-selected', index + 1); } }); }); }); 
 .selected { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input type="checkbox" class="item">Item 1</label> <label><input type="checkbox" class="item">Item 2</label> <label><input type="checkbox" class="item">Item 3</label> <label><input type="checkbox" class="item">Item 4</label> <label><input type="checkbox" class="item">Item 5</label> <label><input type="checkbox" class="item">Item 6</label> 


注意 :您可以使用.data.removeData替換.attr.removeAttr ,但只有前者才能看到DOM上的更改。 jQuery數據(即.data )僅保留數據的內部緩存,不會影響DOM樹。 在你的情況下,這兩個都很好,這是一個選擇的問題。

如何檢查.item類的所有元素是否具有屬性,如果沒有,則執行某些操作。

var items = $('.item');
var itemsWithoutAttribute = items.filter(':not([data-selected]');
if(itemsWithoutAttribute.length > 0) {
    ...
}

暫無
暫無

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

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