簡體   English   中英

從表格單元格中的選擇獲取文本

[英]Get text from select in table cell

使用原始javascript或jQuery,我需要從表單元格中的選擇中獲取文本。 我已經附上了我必須工作的代碼,幾乎可以得到我所需要的代碼。

var tbl = document.getElementById('tblHours');
var rowCount = tbl.rows.length;
var colCount = tbl.rows[0].cells.length;

for (var i = 0;i<rowCount;i++) {
    var myrow = tbl.rows[i];
    for (var j=0;j<colCount;j++) {
        alert(myrow.cells[j].firstChild.innerHTML);
    }
}

這段代碼的問題是它使我獲得了用於選擇的原始html,並且我需要知道實際選擇了什么文本。 謝謝!

切換到jQuery!

var tbl = $('#tblHours');

tbl.find('tr').each(function(){
   $(this).find('td').each(function(){
       alert($(this).find('select :selected').val());
   });
});

我沒有測試代碼。 僅舉例來說。

如果您嘗試通過此功能從其中剝離html或僅使用其中的代碼怎么辦

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}
for (var i = 0;i<$('#tblHours tr').length;i++) {
    var myrow = $('#tblHours').find('td');
    for (var j=0;j<myrow .length;j++) {
        alert(myrow.text());
    }
}

對於HTML中的選定選項,請參考: http : //api.jquery.com/selected-selector/

嘗試以下代碼(未經測試):

var tbl = document.getElementById('tblHours');
var rowCount = tbl.rows.length;
var colCount = tbl.rows[0].cells.length;

for (var i = 0;i<rowCount;i++) {
    var myrow = tbl.rows[i];
    for (var j=0;j<colCount;j++) {
        alert($(myrow.cells[j]).find('select :selected'));
    }
}

暫無
暫無

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

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