【问题标题】:Jquery bind click event to all form fields using delegateJquery使用委托将点击事件绑定到所有表单字段
【发布时间】:2014-01-17 15:30:15
【问题描述】:

这是我的 HTML

<div class="dc2-contact-cont" selectedindex="1" id="contact-form-applet">
<div class="dc2-ltfc">
    <div class="dc2-ltfcs">A
        <br>
    </div>
    <div role="row" class="dc2-ltfcc" id="0">
        <p><span class="dc2-ltf-span" id="SIO_Contact_First_Name_Label">First Name</span>
            <br>
            <input type="text" aria-labelledby="SIO_Contact_First_Name_Label" id="0_SIO_Contact_First_Name" name="s_5_2_30_0" class="dc2-ltf-input" value="555" aria-readonly="false">
        </p>
    </div>
</div>
<div class="dc2-ltfc">
    <div class="dc2-ltfcs">B
        <br>
    </div>
    <div role="row" class="dc2-ltfcc" id="1">
        <p><span class="dc2-ltf-span" id="SIO_Contact_First_Name_Label">First Name</span>
            <br>
            <input type="text" aria-labelledby="SIO_Contact_First_Name_Label" id="1_SIO_Contact_First_Name" name="s_5_2_30_0" class="dc2-ltf-input" value="4444">
        </p>
    </div>
</div>

我需要将点击事件绑定到 div 内的所有输入控件,但我无法找到正确的选择器。

我尝试了以下表达式,但没有成功

$('.dc2-ltfcc p').delegate("input[type=text], textarea",
    "click", {
        ctx: this
    },
    function(event){
        console.log("clicked");             
    });

这是 jsFiddle 的链接,我尝试使用 find 来获取正确的选择器,但我什至无法选择 div。

jsFiddle

【问题讨论】:

  • 我认为委托中的 {cts:this} 出错了。谁能给出正确答案?
  • ctx:这是对的。它传递当前函数的上下文

标签: javascript jquery html


【解决方案1】:

你可以这样做:

$('.dc2-ltfcc p').on('click','input',function() {
     console.log("clicked");
});

注意:delegate() 已从版本1.7 中弃用,您应该像上面一样使用on()

【讨论】:

  • @Pilot deprecated 不代表removed
【解决方案2】:

使用on

$("#contact-form-applet").on("click","input",function() {
alert('test');
});

Working Demo

使用delegate

$( "#contact-form-applet" ).delegate( "input", "click", function() {
alert('test');
});

Working Demo

【讨论】:

  • 为什么on ..OP 要求.delegate()
【解决方案3】:

使用on()

.on() 语法是 1.7 版使用的新语法,旨在替代 .bind().delegate().live()

了解更多->http://blog.jquery.com/2011/11/03/jquery-1-7-released/

$("#contact-form-applet").on('click','input',function() {

// your desire action     
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多