[英]Get custom attribute from select
如何從所選選項中獲取data-itemslimit
屬性?
$(function() { $('#content_id').on('change', function(){ alert($('#content_id').attr('data-itemslimit')); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <select id="content_id" class="form-control" data-reactid=".2.3.4.2.0.1.0.1.0"> <option value="22" data-itemslimit="9" data-reactid=".2.3.4.2.0.1.0.1.0.$22">Content Test</option> <option value="23" data-itemslimit="6" data-reactid=".2.3.4.2.0.1.0.1.0.$23">Second Content</option> </select>
我得到undefined
...
使用option:selected
$(function() { $('#content_id').on('change', function(){ alert($('option:selected', this).attr('data-itemslimit')); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <select id="content_id" class="form-control" data-reactid=".2.3.4.2.0.1.0.1.0"> <option value="22" data-itemslimit="9" data-reactid=".2.3.4.2.0.1.0.1.0.$22">Content Test</option> <option value="23" data-itemslimit="6" data-reactid=".2.3.4.2.0.1.0.1.0.$23">Second Content</option> </select>
參考
您必須使用$('option:selected',this).attr('data-itemslimit')
因為您的選項具有data-itemslimit
而不是 select 本身。
演示
$(function() { $('#content_id').on('change', function(){ alert($('option:selected',this).attr('data-itemslimit')); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <select id="content_id" class="form-control" data-reactid=".2.3.4.2.0.1.0.1.0"> <option value="22" data-itemslimit="9" data-reactid=".2.3.4.2.0.1.0.1.0.$22">Content Test</option> <option value="23" data-itemslimit="6" data-reactid=".2.3.4.2.0.1.0.1.0.$23">Second Content</option> </select>
您可以使用以下代碼。
$('#content_id').on('change', function(e) {
var data = $(this).children("option:selected").data('itemslimit');
alert(data);
});
使用選項:選擇更改:
js:
$(function() {
$('select').on('change', function(){
alert($('option:selected',this).attr('data-itemslimit'));
})
});
html:
<select id="content_id" class="form-control" data-reactid=".2.3.4.2.0.1.0.1.0">
<option value="22" data-itemslimit="9" data-reactid=".2.3.4.2.0.1.0.1.0.$22">Content Test</option>
<option value="23" data-itemslimit="6" data-reactid=".2.3.4.2.0.1.0.1.0.$23">Second Content</option>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.