[英]Change select option based on attribute
我試圖更改click
的select option
,但我不想使用option value
。 我的代碼工作,如果我給我的按鈕value='3'
,但我要的是選擇一個與data-price="0"
這在我的情況下是一個與value='3'
。
JS:
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option').val(jQuery(this).attr('value'));
});
});
HTML:
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
任何幫助將不勝感激
您可以使用屬性等於選擇器來獲取選項,然后通過使用prop()
方法設置selected
屬性來選擇選項。
jQuery(document).ready(function() { jQuery('#sample-addtocart-button').click(function() { jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button value="0" id="sample-addtocart-button" type="button">Free</button> <select class="product-custom-option"> <option value="">-- Please Select --</option> <option data-price="10" value="1">£10.00</option> <option data-price="20" value="2">£20.00</option> <option data-price="0" value="3">FREE</option> </select>
您可以按屬性選擇元素,然后在元素上設置selected
屬性。
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
});
});
這將選擇data-price
屬性等於this.value
的值的元素,此屬性是.product-custom-option
的后代,並將其selected
屬性設置為true
。
如果沒有jQuery,它可能看起來像這樣:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
少數輔助方法總是可以幫助您提高詳細程度:
function listen(el, typ, fn, cap) {
el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
if (typeof el === "string") {
sel = el;
el = document;
}
return el.querySelector(sel)
}
listen(document, "DOMContentLoaded", function () {
listen(query('#sample-addtocart-button'), "click", function(){
query('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
嘗試這個:
jQuery('#sample-addtocart-button').click(function(){
var val= jQuery(this).attr('value');
jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.