簡體   English   中英

Javascript從表中的選定選項獲取數據屬性

[英]Javascript get data attribute from selected option in a table

我得到以下html:

<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>

我需要獲取所選選項的數據屬性。 我正在嘗試這樣做:

var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');//val(); previously it was val() here but now I want data-key
}

我嘗試了這個:

$(selectObject/*need to insert something here*/ + ' option:selected').data('key');

但是它向我顯示了一個錯誤,說它是一個對象Object。 我需要在selectObject之后插入一些內容。 任何想法如何解決?

謝謝。

使用jquery函數attr()嘗試$('.form-control').children('option:selected').attr('data-key') attr()

 console.log($('.form-control').children('option:selected').attr('data-key')) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td class="" data-id="46" contenteditable="true"> <select class="form-control"> <option data-key="end" selected>Opt1</option> <option data-key="operator_transfer">Opt2</option> <option data-key="process_script">Opt3</option> </select> </td> 

對於您的代碼,您可以這樣做

var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).children('option:selected').data('key');

您只需要使用帶有正確選擇器的jQuery data()方法,如下所示:

$('select option:selected').data('key');

演示:

 var key = $('select option:selected').data('key'); console.log(key); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td class="" data-id="46" contenteditable="true"> <select class="form-control"> <option data-key="end" selected>Opt1</option> <option data-key="operator_transfer">Opt2</option> <option data-key="process_script">Opt3</option> </select> </td> 

您可以像這樣更新代碼:

if (selectObject.length) { // if it is a select
  localobj[dataattr] = selectObject[0].getAttribute('data-key');
}
$(selectObject).find('option:selected').data('key');

 $('.form-control').change(function(){ alert($('.form-control').find(':selected').attr('data-key')); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td class="" data-id="46" contenteditable="true"> <select class="form-control"> <option data-key="end" selected>Opt1</option> <option data-key="operator_transfer">Opt2</option> <option data-key="process_script">Opt3</option> </select> </td> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM