3

I want to set all items of specific class to a specific value, but IF it has a specific attribute set, it must match a condition.

Example:

<div class="address"></div>
<div class="address" data-address-type="from"></div>
<div class="address" data-address-type="to"></div>

I want to set all address to "123 Some Address Road". However, if there is a data-address-type, only if the data-address-type is "to".

$('.address[data-address-type="to"]').text('123 Some Address Road');

The above will not change the elements where data-address-type is not defined.

4

3 回答 3

7

您需要为此使用 a filter(),在.address元素中过滤元素,这些元素要么不具有使用data-address-type属性,:not([data-address-type])要么具有使用data-address-typeto[data-address-type="to"]

$('.address').filter(':not([data-address-type]), [data-address-type="to"]').html('')

演示:小提琴

于 2013-10-31T04:54:53.060 回答
3

尝试这个:

[data-address-type='to']表示attribute数据地址类型value等于。

$(".address[data-address-type='to'],.address:not([data-address-type])").text("123 Some Address Road");

在这里拉小提琴。

更多信息在这里。

于 2013-10-31T04:52:57.407 回答
0

使用$(".address")和的组合Attribute Equals SelectorAttribute Not Equal Selector

于 2013-10-31T04:55:20.757 回答