Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery插件选择带有“";这";要素_Jquery_Jquery Plugins - Fatal编程技术网

jQuery插件选择带有“";这";要素

jQuery插件选择带有“";这";要素,jquery,jquery-plugins,Jquery,Jquery Plugins,如果我有两个这样的html表: <table id="myTable"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Total</th> <th>Discount</th>

如果我有两个这样的html表:

<table id="myTable">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
      <th>Total</th>
      <th>Discount</th>
      <th>Difference</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Peter</td>
      <td>Parker</td>
      <td>28</td>
      <td>$9.99</td>
      <td>20.9%</td>
      <td>+12.1</td>
      <td>Jul 6, 2006 8:14 AM</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Hood</td>
      <td>33</td>
      <td>$19.99</td>
      <td>25%</td>
      <td>+12</td>
      <td>Dec 10, 2002 5:14 AM</td>
    </tr>
  </tbody>
</table>
<br/><br/>
<table id="anotherTable">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>High Score</th>
      <th>Total Score</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Clark</td>
      <td>Kent</td>
      <td>18</td>
      <td>32</td>
    </tr>
    <tr>
      <td>Bruce</td>
      <td>Almighty</td>
      <td>45</td>
      <td>180</td>
    </tr>
  </tbody>
</table>
我正在创建一个jQuery插件,我希望能够使用$(“table”).myplugin()或$(“#myTable”).myplugin()将其应用于我的应用程序中页面上的任何或所有HTML表

在我的插件代码中:

return this.each(function(index){
    // code here
});
如果我添加行
$(this).addClass('myClass')
CSS“myClass”将添加到表“myTable”中,但如果我添加行
$('thead')。addClass()
“myClass”将添加到两个thead中。我尝试了
$(this thead).addClass(),$(this'thead').addClass(),$('this thead').addClass()
,但是所有的都会抛出一个JS错误。如何利用“this”仅选择“myplugin”元素中应用于本例中的“myTable”中的thead?

您可以使用

如果您确定
thead
this
的直接子项,则可以改用,而且速度会更快,尤其是当您有非常大的表时

$(this).children("thead").addClass();
您还可以将
设置为查询的上下文:

$("thead", this).addClass();
尝试:
$(this.find(“thead”).addClass(“myClass”)

啊哈,$('thead',this).addClass();这正是我想要的。此时我试图避免使用$(this.find(“thead”),因为在我的代码后面,我想为th添加一个不同的类。所以我在正确的页面上,我应该能够这样做:$('thead',this.find(“th”).addClass()?对您还可以链接
.find
s:
$(this).find(“thead”).find(“th”)
。我确实读到插件返回jquery对象进行链接。我不确定我之前做了什么,但它没有正常工作。但是,我喜欢$('thead',this).find(),因为它在代码中看起来更干净。
$(this).children("thead").addClass();
$("thead", this).addClass();