2016-07-19 9 views
0

行のテキストに基づいて:私はjqueryのを使用することはできません状況にいることから、通常のjavascriptにSelect table row and check checkbox using JQueryJavascriptのチェックボックス私は、この変換しようとしています

を。ここで

のorignal

$("table tr").each(function() { 
    if ($(this).find("td:eq(1)").text().trim() == '2013-03-21') { 
    $(this).find("input[type=checkbox]").attr("checked", true); 
    } 
}); 

これは私がこれまで持っているものである、と私はその方法オフ確信している:

var elements = [].slice.call(document.querySelectorAll("table tr")); 

Array.prototype.forEach(elements, function(){ 
var tdText = this.querySelectorAll("td").textContent 
if (tdText == '2013-03-21') { 
    this.querySelectorAll("input[type=checkbox]").setAttribute("checked", true); 
    } 
}); 

これは元のテーブルです:

<table> 
    <tr> 
     <td>Record1</td> 
     <td>2013-03-21</td> 
     <td> 
      <input type="checkbox" /> 
     </td> 
    </tr> 
    <tr> 
     <td>Record2</td> 
     <td>2013-03-22</td> 
     <td> 
      <input type="checkbox" /> 
     </td> 
    </tr> 
    <tr> 
     <td>Record3</td> 
     <td>2013-03-21</td> 
     <td> 
      <input type="checkbox" /> 
     </td> 
    </tr> 
</table> 

答えて

0

querySelectorAll()は、要素のnodeListを返します。あなたはtrNodeListを参照しているので

element.querySelectorAll("td")[0] 
+0

itemで慰め。 http://jsfiddle.net/Fdhyp/158/まだ動作していません。 – t67

+0

コードには問題がたくさんあります...試してみてくださいhttp://jsfiddle.net/Fdhyp/160/ – charlietfl

+0

ありがとうございます。 – t67

0

コードvar tdText = this.querySelectorAll("td").textContentが未定義のTextContentを返します。

あなたが好きなもの反復処理し、各インスタンスに対処するかしたいインデックスを使用する必要があります。もしあなたがtdのコンテンツを取得することができ、それをループとすることができます:td要素からテキストを選択しながら

let rows = Array.prototype.slice.call(document.querySelectorAll('table tr')); 
let textDate = '2013-03-21'; 

rows.map((row) => { 
    let cells = Array.prototype.slice.call(row.querySelectorAll('td')); 
    for (let i = 0, length = cells.length; i < length; i++) { 
     if (cells[i].textContent === textDate) { 
      let cb = row.querySelectorAll('input[type=checkbox]'); 
      cb[0].checked = true; 
      return; 
     } 
    } 
}); 
0
  • 使用ElemCollection.forEach.call代わりHTMLCollectionとしてArray#slice.callを使用するにはforEach方法
  • 使用[1]インデックスを持っていません
  • thisArray#forEachelementを参照していません。first引数のArray#forEachコールバックf私はちょうど二tdからテキストを引くことができarray

Array.prototype.forEach.call(document.querySelectorAll("table tr"), function(elem) { 
 
    var tdText = elem.querySelectorAll("td")[1].textContent; 
 
    if (tdText === '2013-03-21') { 
 
    elem.querySelector("input[type=checkbox]").setAttribute("checked", true); 
 
    } 
 
});
<table> 
 
    <tr> 
 
    <td>Record1</td> 
 
    <td>2013-03-21</td> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td>Record2</td> 
 
    <td>2013-03-22</td> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td>Record3</td> 
 
    <td>2013-03-21</td> 
 
    <td> 
 
     <input type="checkbox" /> 
 
    </td> 
 
    </tr> 
 
</table>

関連する問題