我有以下代码:
<div class="checkout-related-view__related-row">
<div class="checkout-related-view__related-row-cell checkout-related-view__related-row-cell--left">
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox-7087458-Z22-00025" value="2536" data-role="none">
<label for="related-checkbox-7087458-Z22-00025">
<span class="checkbox"></span>
TV Bed or Adjustable Bed Assembly</label>
</div>
<div class="checkout-related-view__related-row-cell checkout-related-view__related-row-cell--right">
<span class="price"><span class="currency">£</span>0</span>
<a href="javascript:void(0)" class="checkout-icon checkout-icon-info related-info" data-toggle="popover" title="" data-content="When your new TV or Adjustable bed is delivered we will take care of all the assembly required, completely free of charge."
data-html="true" data-trigger="focus" tabindex="0" data-original-title="Free Assembly">
<span class="visuallyhidden">Free Assembly</span>
</a>
</div>
<div class="checkout-related-view__related-row-cell checkout-related-view__related-row-cell--qty">
<div class="input-combobox input-combobox__with-qty" data-label="Qty" data-range-min="0" data-range-max="1">
<span class="input-combobox__label">Qty</span>
<input class="input-combobox__text input-qty" type="text" name="related_products[7087458][2536][qty]" value="0">
</div>
</div>
</div>
我正在研究如何检查该 block 是否包含电视床或可调节床组件以将数量值更改为“1”。到目前为止,我已经设法使用以下 JS 将值更改为“1”:
document.getElementsByClassName("input-combobox__text input-qty")[2].value = "1";
我现在遇到的问题是实际放置一个仅在“TV Bed or Adjustable bed”时才执行 JS 的逻辑。我试过 :contains
但它似乎没有用。你能帮忙吗?
场景:
2 个相同类别的产品:
第一个是木床
第二个产品是电视床
目前:
如果 JS 捕捉到包含电视床的标签和文本,它将对第一个项目应用数量 1,无论它是电视床还是木床
最终目标:
如果电视床存在,则只对相关产品设置数量为 1
目前我指的是数组并定义要更改的数量。我也将其称为 ".input-combobox__text.input-qty"
有什么方法可以使用 name="related_products[7087458][2536][qty ]"
最佳答案
这里是一种检查和设置的方法:
fiddle :https://jsfiddle.net/ckuxzxms/1/
纯JS
var label = document.querySelector('[for="related-checkbox-7087458-Z22-00025"]');
if (label) {
var text = label.textContent.trim();
if (text == 'TV Bed or Adjustable Bed Assembly') {
document.querySelectorAll(".input-combobox__text.input-qty")[0].value = "1";
}
}
使用 querySelector 获取标签,检查它是否找到任何内容,如果找到,则获取 textContent 并删除所有空白。然后检查直接相等性。稍微更改值的设置以使用 querySelectorAll 而不是 getElementsByClassName。
jQuery: https://jsfiddle.net/ckuxzxms/2/
var label = $('[for="related-checkbox-7087458-Z22-00025"]');
if (label.length > 0) {
var text = label.text().trim();
if (text == 'TV Bed or Adjustable Bed Assembly') {
$(".input-combobox__text.input-qty").val("1");
}
}
关于javascript - 检查元素是否存在并开始一些事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793396/