【问题标题】:How to execute a function using the value of a textbox Onclick of a DIV instead of a Onclick of a textbox如何使用文本框的值执行函数 DIV 的 Onclick 而不是文本框的 Onclick
【发布时间】:2011-06-10 04:40:48
【问题描述】:

我有这个功能:

$("#border-radius").click(function(){   
var value = $("#border-radius").attr("value");
    $("div.editable").click(function (e) { 

       e.stopPropagation();

       showUser(value, '2', this.id)
       $(this).css({
          "-webkit-border-radius": value
       });  
    });                      
});

它读取文本框的值,

input type="text" id="border-radius" value="20px"

...并用它做一些与我的问题无关的事情。

文本框有id="border-radius",当它被点击(并且有值)时函数执行,如图:$("#border-radius").click(function(){ ...do some stuff...

基本上,我希望能够在文本框中输入一个值,然后单击一个对象(提交按钮或 div,最好是一个 div)并让它在之后执行函数:$("#border-radius").click(function(){ ...do some stuff... 而不必单击文本框本身

我可以添加/更改什么来启用它?

【问题讨论】:

  • 只需将 $("#border-radius").click 更改为 $("#otherdiv").click
  • 我认为这很简单
  • 应该把它作为答案发布:|确定我错过了您的描述中的某些内容

标签: javascript jquery jquery-selectors


【解决方案1】:

我认为您需要确定事件目标。

你可以这样做

事件目标属性

例子

$(document).ready(function() {
    $("#border-radius").click(function(event) {
        alert(event.target.id);
       //match target id and than proceed futher 
    });
});

【讨论】:

  • 哇,让我们把事情变得更复杂;)))
  • @mplungjan = 有什么复杂的..你需要确定事件的悲剧就是这样
【解决方案2】:

将点击处理程序放在#my-button 或任何您的按钮上。

$("#my-button").click(function(){
    var value = ... /* your original code */
});

它仍然有效,因为您获得的值类似于 $("#border-radius").attr("value"); 而不是 $(this).attr("value");。因此,您需要更改的只是将点击功能附加到哪个元素。

或者,如果您想保留两个处理程序,您可以将它用于两个元素,如下所示:

var commonHandler = function(){   
    var value = ... /* your original code */
};

$("#border-radius").click(commonHandler);
$("#my-button").click(commonHandler);

你也可以触发#border-radius的点击事件,但这会执行所有附加在它上面的事件处理器:

$("#my-button").click(function () {
     $("#border-radius").click();
     // or $("#border-radius").trigger('click');
});

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多