jQuery:选择在另一个指定元素之后发生的元素的第一个实例

时间:2010-02-04 19:48:17

标签: javascript jquery jquery-selectors

使用它作为简化示例,假设我有一个表中有一些单选按钮,后跟一个带有链接的div元素。然后,这种模式重复一些未知的次数,如下所示:

<table class="rdoBtnList">
    <tbody>
       <tr>
          <td> Person 1 </td>
          <td>
            <label for="rb1">Verified</label>
            <input type="radio" id="rb1" name="rdoBtns" value="Verified" />
            <label for="rb2">Not Verified</label>
            <input type="radio" id="rb2" name="rdoBtns" value="NotVerified" />
          </td>
       </tr>
    </tbody>
 </table>
 <div class="PersonLink"><a href="#">Link to Person 1 page</a></div>
  ..... tables and divs for person 2, 3, ... n, etc

我希望能够使用jQuery根据单选按钮的值启用/禁用单选按钮后面div中的链接。我可以得到单选按钮的值,但无法弄清楚我会用什么选择器语法来启用/禁用只是单选按钮后的div。

到目前为止,这是我的jQuery:

    <script type="text/javascript">
       $(document).ready(function() {
           $(".rdoBtnList > tbody > tr > td > input").change(function() {
           if ($(this).val() == "Verified") {
               // select the link in the div following the table and enable it
           } else {
               // select the link in the div following the table and disable it
           }
        });
       });
    </script>

2 个答案:

答案 0 :(得分:4)

像这样:

$(this).closest('.rdoBtnList').nextAll('.PersonLink:first').children('a').whatever

closest('.rdoBtnList')会找到该表格,nextAll('.PersonLink:first')会在表格后面找到第一个.PersonLink

顺便说一下,val函数返回一个普通的布尔值。你应该写if($(this).val())

答案 1 :(得分:0)

我会尝试不同的方法,给每个链接一个id,或者甚至是一个类,以便于选择:

<table>...
    <input type="radio" id="personXrb1" class="personXselector" ...
<div>
<a href="personXlink" id="personXselector">link to person X</a>

这应该相对简单,因为我希望以编程方式生成html。对?由于代码更改,它也不太容易出错,并且可能更容易阅读。

然后不会使用$(this).closest等进行选择,在更改代码后无法保证工作,而是通过

$('#' + $(this).attr('class')).doStuff();

我也不确定启用/禁用是否可以使用div或a-tag,你可能最好使用fadeOut()和fadeIn()或者只使用show()和hide()来“禁用”链接。

相关问题