【问题标题】:How do I bind functions to all input elements using jQuery?如何使用 jQuery 将函数绑定到所有输入元素?
【发布时间】:2011-01-30 17:00:50
【问题描述】:

假设我有这套 HTML 标记和 CSS

#CSS

.inputhelp_text { background: #000; color: #fff; }
.nodisplay { display: none; }

<input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname">Write in your firstname</span>

<input class="inputhelp" id="lastname" /><span class="inputhelp_text nodisplay" id="help_lastname">Write in your lastname</span>

使用 jQuery,我需要将一个函数绑定到所有输入字段(我猜是使用 jQuery 的 EACH 函数),这样当我单击输入字段时,它应该将每个跨度的类切换为仅“inputhelp_text”。我已经让它在每个字段的两个单独的函数中工作,但由于我有很多字段,我知道有更好的方法来解决它。

有什么建议吗?

【问题讨论】:

  • 我不习惯 jQuery,所以即使是手动的,事情开始也很慢。 “谢谢”你。
  • 这就是为什么阅读文档可能会有用。

标签: jquery html css function each


【解决方案1】:

我在这种情况下所做的如下。假设您有一组$("input"),您想以某种方式绑定到它们,例如您想在它们为空时添加一个.invalid 类:

$("input").each(function () {
      var $this = $(this);
      $this.focus(function (e) {
        $this.removeClass("invalid");
      });

      $this.blur(function (e) {
        if ($this.val() == "") {
          $this.addClass("invalid");
        }
      });
    });

通过存储对从$.fn.each 返回的$(this) 的引用,您现在可以单独绑定到每个元素上的事件。

【讨论】:

    【解决方案2】:

    您希望将处理程序绑定到 blur()focus() 事件:

    $(".inputhelp").focus(function() {
      $("span.inputhelp_text:visible").addClass("nodisplay");
      $(this).next("span.inputhelp_text").removeClass("nodisplay");
    }).blur(function() {
      $("span.inputhelp_text").addClass("nodisplay");
    });
    

    通常我建议使用像hide()show() 这样的jQuery 效果,但这些效果只适用于块级元素。 &lt;span&gt; 是内联的,所以这不起作用。

    【讨论】:

    • @bakkelun 详细信息无疑会很有用
    【解决方案3】:

    你可以使用 each 函数:

    $("input").each(function() {
      // this points to the input DOM element
      // $(this) is the jQuery wrapped element
    });
    

    例如,您可以:

    $(this).removeClass("inputhelp");
    $(this).addClass("inputhelp_text");
    

    在回调内部。

    【讨论】:

    • 这个也可以吗??选择“inputhelp”类的所有输入? $('input[class=inputhelp]').bind('focus',function() { // 做点什么 }
    • 是的,但是 $("input.inputhelp") 或 $(".inputhelp") 是做同样事情的更简单的选择器。
    • 请记住,较短(更非特定)的触发器会使在 DOM 中的搜索速度变慢。很像 xpath 查询;指定更长更具体的路径会加快查询速度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多