【问题标题】:jQuery: selecting the first instance of an element that occurs after another specified elementjQuery:选择在另一个指定元素之后出现的元素的第一个实例
【发布时间】:2010-02-05 23:22:59
【问题描述】:

使用这个作为一个简化的例子,假设我有一个表,其中有一些单选按钮,后跟一个带有链接的 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 中的链接。我可以获得单选按钮的值,但无法弄清楚我将使用什么选择器语法来启用/禁用 just 单选按钮之后的 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>

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    像这样:

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

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

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

    【讨论】:

    • 这种方法看起来不错,但在我的实际代码中,我最终不得不比在这个示例中进行更多的遍历。您的代码向我展示了如何做到这一点! if($(this).val() == "True") 也是我的错字,应该是 if($(this).val() == "Verified")。我编辑了我的帖子以反映这一点。谢谢!
    【解决方案2】:

    我会尝试不同的方法,给每个链接一个 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() 来“禁用”链接。

    【讨论】:

    • 感谢您的回答。我无法更改 ID,因为它们是通过 asp.net 在我无法更改的旧代码中生成的。我最终只是用 css() 函数隐藏了链接。
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多