2016-06-10 197 views
1

我试图更改select optionclick但我不想使用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> 

任何帮助将不胜感激

回答

2

您可以使用attribute equals selector获取选项,然后通过设置selected属性使用prop()方法来选择选项。

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>

+1

干杯队友,非常感谢! – Genov

1

您可以通过属性选择元素,然后设置元素的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; 
    }); 
}); 
+0

干杯伴侣,非常感谢! – Genov

+0

我的荣幸。很高兴帮助。 – 2016-06-10 14:03:56

0

试试这个:

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 
});