这是HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">
$20
</span>
<p id="in-carHEREt" style="display: none;">in cartHERE</p>
<span class="needsclick select-widget enabled" id="size-options-link">Medium</span>
<select id="size-options" name="size-options" class="select-widget ">
<option value="46158">Medium</option>
<option value="46159">Large</option>
<option value="46160">XLarge</option>
</select>
<span id="cart-update"><span class="cart-button">add to cart</span></span>
我尝试了以下操作,但它不会更改选项,停留在“中”位置。
document.getElementById("size-options").value = "Large"
document.getElementById("size-options").dispatchEvent(new Event('change'))
document.getElementById("size-options-link").dispatchEvent(new Event('click'))
document.getElementById("size-options-link").value = "Large"
我不知道如何选择大。
我们非常感谢您的帮助,我需要像上面那样的答案,因为我正在迅速地将它用于名为validatejavascript的函数中。
谢谢
答案 0 :(得分:1)
查看内联评论:
// Get all the options into an array
let options = Array.prototype.slice.call(document.querySelectorAll("#size-options > option"));
// Use Array.filter() to locate just the one with the text of "Large"
let large = options.filter(function(item){
return item.textContent === "Large";
});
// Get the value of that item and set that as the <select> value
document.getElementById("size-options").value = large[0].value;
document.getElementById("size-options").dispatchEvent(new Event('change')) // Fire the change event
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">$20</span>
<p id="in-carHEREt" style="display: none;">in cartHERE</p>
<span class="needsclick select-widget enabled" id="size-options-link">Medium</span>
<select id="size-options" name="size-options" class="select-widget ">
<option value="46158">Medium</option>
<option value="46159">Large</option>
<option value="46160">XLarge</option>
</select>
<span id="cart-update"><span class="cart-button">add to cart</span></span>
答案 1 :(得分:0)
您错误地设置了<option>
的显示文本,而不是其值。您必须将46159设置为值。
document.getElementById("size-options").value = "46159"
document.getElementById("size-options").dispatchEvent(new Event('change'))