簡體   English   中英

與在jquery中獲取類名相關的問題

[英]Issue related to getting class name in jquery

我有以下HTML:

<table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
  <tr class="row1">
    <td></td>
  </tr>
  <tr class="row2">
    <td></td>
  </tr>
</table>

和以下jQuery:

<script>
$(document).ready(function () {
  var Tabletr= $(".ChatBox > tbody >  tr:odd");
});
</script>

如何在Jquery中獲得Odd行的類名?

簡單地var $elems = $("table.ChatBox tr:odd"); 應該管用。

要獲得他們的課程(請訪問下面的Juicy Scripter),

$elems.each(function(){   console.log(this.className); //do whatever with the class names. });

除了在獲取元素后使用jQuery的attr方法或JavaScript中的元素的className屬性之外,jQuery本身不提供直接檢索DOM元素類的方法:

$(document).ready(function () {
  var Tabletr= $(".ChatBox > tbody >  tr:odd");

  var firstElementClass = Tabletr.eq(0).attr('class');

  // Previous is the same as
  var firstElementClass = Tabletr.get(0).className;

  // Due to fact that Tabletr may contain more that one row you may want to iterate and collect classes names.
  var classes = [];
  Tabletr.each(function(){
    classes.push(this.className);
    // OR
    classes.push($(this).attr('class'));
  });
});

試試這個:

<script>
    $(document).ready(function () {
        var Tabletr= $(".ChatBox").children("td:odd").attr("class");
        alert (Tabletr);
        }
    });
</script>

如果你想得到第一個td類,你也可以使用:first而不是:odd。

您可以簡化選擇器:

var Tabletr = $(".ChatBox tr:odd")

這為您的表中的每個奇數行提供了一個jQuery對象。 如果只有一個這樣的行,你可以這樣做:

var Tabletr = $('.ChatBox tr:odd')[0].className; // -> "row2"

但是如果有多行,你需要更像這樣的東西:

var TableRowClasses = $(".ChatBox tr:odd").map( function(){
  return this.className;
}).get();

這為您提供了一個數組,其中每個奇數行的類都是一個元素。 所以你最終得到一個像這樣的數組:

["row2","row4","row6"] // confusing odd-row classnames notwithstanding

我看了你的代碼,以下的更改給了我你的結果。

  <table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
        <tr class="row1">
        <td></td>
        </tr>
        <tr class="row2">
            <td></td>
        </tr>

       <tr class="row3">
            <td></td>
        </tr>

       <tr class="row4">
            <td></td>
        </tr>
    </table>

 <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
 <script type="text/javascript">
     $(function () {

         $(".ChatBox tr:odd").each(function () {
             //test
             alert($(this).attr("class"));
         });

     });
 </script>

暫無
暫無

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

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