jQuery-如何从元素列表中选择具有类名的元素

时间:2014-11-21 20:18:55

标签: javascript jquery closest

我正在使用jQuery。

我想从表格中选择一个单元格。 所以我尝试了以下代码。

 // First line works fine for me. I can get a list of columns at the correct target row.
 var targetColumns = $(elemClicked).closest("tr").find("td"); 

 // I want to get the cell with the class named "draftstatus". This line has problem. I cannot get what I want.
 var targetCell = columnsAtTargetRow.$(".draftstatus");

从浏览器检查的targetColumns如下所示: enter image description here

上面的第5个td是我的目标细胞。

我也尝试使用find()函数。它不会起作用,因为find()将从下一个孩子级别开始。

     columnsAtTargetRow.find(".draftstatus"); // this does not work.

我应该使用哪些函数将该单元格放在td"的列表中。

提前致谢。

2 个答案:

答案 0 :(得分:0)

这是不正确的:

columnsAtTargetRow.$(".myclass");

这应该是:

columnsAtTargetRow.find(".myclass");

答案 1 :(得分:0)

您只需确定要使用的选择器。

var targetColumns = $(elemClicked).closest("tr").find("td"); 

这会将DOM上升到" tr"并选择tds。如果 elemClicked 在td中,您可以选择最接近的tds(" td"),然后使用兄弟姐妹(" .draftstatus");

如果elemClicked是td,那么你可以使用兄弟姐妹(" .draftstatus");

以下是一些示例代码,可帮助演示一些选择器。希望这有助于一些人,而不是让你更加困惑。



$(function(){
    
    
    //reference all cells with myclass class using filter
    $("#table1 tbody td").filter(".myclass").addClass("red");

    // click events for all tds reference the .target class cell using siblings
    $("#table1 tbody td").on("click",function(e){
        $(this).siblings(".target").toggleClass("red");
    }); 
    
  
  //items inside a table cell click event
    $("#table1 tbody td a").on("click",function(e){
      //toggle bold class
        $(this).closest("td").siblings(".target").toggleClass("bold");
          //prevent event from bubbling up 
          e.stopPropagation();
    }); 
})

.red {
    background-color:red;
}

.bold { font-weight:bold; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table border="1" id="table1">
    <tbody>
        <tr>
            <td>foo</td>
            <td>bar</td>
            <td class="myclass target">value2</td>
            <td>Two <a href="#">link</a></td>
        </tr>
      
       <tr>
            <td>foo</td>
            <td>bar</td>
            <td class="myclass target">value2</td>
            <td>Two <a href="#">link</a></td>
        </tr>
      
    </tbody>
</table>
&#13;
&#13;
&#13;

相关问题