【问题标题】:jQuery - get next element with same name as id of selected inputjQuery - 获取与所选输入的 id 同名的下一个元素
【发布时间】:2011-10-12 00:55:51
【问题描述】:

首先,我想为那里的可怕标题道歉,但这是我能想到的总结问题的最佳方式。

目前,我使用jQuery 脚本在blurinput:text 上检查输入的文本值是否大于一定数量。如果不是,则输入会以红色突出显示 - 但我接下来想做的是在相邻列中有一个 <p> 以更改其文本。

我的 HTML 如下所示:

<tr>
      <td width="15%"><label for="example">Hello world</label></td>
      <td width="70%"><input type="text" class="" id="example" value=""/></td>
      <td width="15%"><p name="example"></p></td>
 </tr>

我的 jQuery/css 是:

<style type="text/css">
    .fail{
        border:2px red solid;
    }   
    </style>

    <script type="text/javascript">
    /* Inline, onBlur validation 
    Text */
    $('input:text').blur(function() {
        if ($(this).val().length <= 2) {
            $(this).attr('class', 'fail');
            }else{$(this).attr('class', '');}
    });
    </script>

是否有可能在blur 上以与所选输入的id 相同的name 调用下一个元素,然后更改其文本?我知道这一定是一个很难解决的动态难题,但这是我真正需要的。

过去,我通过对每个元素重复代码来达到相同的效果,但这并不适合这里。

感谢您给我的任何建议!

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    zzzzBov 是正确的,但是最好使用上下文来提高效率和/或标记名。另外添加一个引用 $(this) 的变量。

    var $this = $(this);
    $('p[name="'+$this.attr('id')+'"]', $this.closest('tr')).text('foo bar baz'); 
    

    评论后编辑 上面和zzzzBov的回答的区别是:

    $('[name="'+$(this).attr('id')+'"]')  
    // will start traversing the DOM starting at the beginning of the 
    // document. Largest search.
    
    $('p[name="'+$this.attr('id')+'"]')
    // will first call getElementsByTagName and try to find a match, smaller search.
    
    $('p[name="'+$this.attr('id')+'"]', $this.closest('tr'))
    // will only search the contents of the closest('tr') tag 
    // that is an ancestor of your input. Even smaller search.
    

    一般来说,更具体地使用 jQuery 选择器可以提高性能。此外,使用变量来存储诸如var $this = $(this);var $myElement = $('#myElement') 之类的选定元素比一遍又一遍地创建相同的选择器更有效。请记住,jQuery 与选择器一样高效,但您可以利用它们来发挥潜力。

    【讨论】:

    • John Hartsock 与使用parent 的@zzzzBov 有何不同?我还是 jQuery 的新手,所以请原谅我在那里的无知...
    • 啊,谢谢你,John,我现在就试试……我什至没有想到那种效率。谢谢!鉴于您在那里的额外帮助,我已经给了您我的标记 - 感谢您的帮助!
    • $(foo, bar) 等价于$(bar).find(foo)
    • 另外,虽然我完全同意使用上下文,但不要过早优化
    【解决方案2】:

    blur 回调的上下文中:

    $('[name="'+$(this).attr('id')+'"]').text('foo bar baz');
    

    【讨论】:

    • 这对我来说非常有效,非常感谢!出于兴趣,这个 sn-p 应该可以改变所有其他属性,对吧?如,如果使用$('[name="'+$(this).attr('id')+'"]').attr('class', 'fail-text');...?
    • 你想使用addClass函数给一个dom节点添加一个类。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 2022-12-21
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多