Jquery抓住另一个控件的同一div内的控件

时间:2009-06-15 09:52:15

标签: jquery

我有一组表示一组字段的div。我想要实现的是,点击一个文本框,你可以获得与“hint”类在同一div内的div。

例如,如果我点击“txtUsername”,我应该得到“usernameHint”

这是html

        <div class="formfield">
            <label class="desc" id="lblUsername" runat="server">Username</label>
            <input type="text"  id="txtUsername" runat="server" class="field text medium" />
            <div id="usernameHint" class="hint" runat="server"></div>               
            <div id="usernameError" runat="server"></div>   
        </div>

        <div class="formfield">
        <label class="desc" id="lblPassword" runat="server">Password</label>
        <input type="password" id="txtPassword" runat="server" class="field text medium" /> 
        <div id="passwordHint" class="hint" runat="server"></div>    
        <div id="passwordError" runat="server"></div>  
        </div>

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

$('#txtUsername').click(function() {
    $(this).parent().find('.hint').text('Must be between 5 and 12 characters in length');
});

选择文本框的父级,即<div class="formfield">,然后在其中找到包含提示类的元素,从而无需使用ID和更复杂的方法获取包含的提示div。

答案 1 :(得分:0)

var hints = (function () {
   /**
    * @var Default selector to display hints for
    */
   var defaultSelector = 'input[type=text]',
   /**
    * This object contains all the public methods.
    */
       handlers = {
         /**
          * Apply fn on the hint-element belonging to the context element
          */
          action: function (fn) {
             var hint = $(this).parent().find('.hint');
             if(hint) {
                hint[fn]();
             }
         },
        /**
         * Show the hint of the element that received focus
         */
         focusListener: function () {
             handlers.action.call(this, 'show');
         },
        /**
         * Hide the hint of the element that lost focus
         */
         blurListener: function () {
             handlers.action.call(this, 'hide');
         },
         /**
          * Initialize listeners for the elements matched by selector
          * @param string [specificSelector] Override the default selector
          * with another one
          */
         init: function (specificSelector) {
            var selector = specificSelector || defaultSelector;
            $(selector).focus(handlers.focusListener);
            $(selector).blur(handlers.blurListener);
         }
      };
   return handlers;
}());

可以这样调用此对象以添加提示功能:

hints.init(); // Add focus and blur listeners on all input-text elements

// Add focus and blur listeners on all input-text and radio elements
hints.init('input[type=text], input[type=radio]');