[英]jQuery ON function with values assigned to parameters
I am trying to delegate a function with a change in radio button selection. 我试图通过更改单选按钮选择来委派一个函数。
$(document).ready(function(){
$('body').on('change', 'radioBtnName', function(e){
$(this).after('<p>"No click me!"</p>');
});
});
What I want to be able to do is to pass some values to the handler function. 我想要做的是将一些值传递给处理函数。 Like
喜欢
{param1:"hell", param2:"world"}
And then to access these values inside the function (e) by 然后在函数(e)中访问这些值
e.data.param1
How do I include these parameters and give them values in setting the delegate. 如何包含这些参数并在设置委托时赋予它们值。 I am creating the radio buttons on the fly and want to associate the function with a change in selection.
我正在创建单选按钮,并希望将该功能与选择中的更改相关联。
This could be easily done with data-*
attributes if they are per element. 如果
data-*
属性是每个元素,则可以使用data-*
属性轻松完成。 So have the button with: 所以有按钮:
<input type="radio" data-param1="hell" data-param2="world" />
And get them using: 让他们使用:
$(this).data("param1");
$(this).data("param2");
Also, if you call the $(this).data()
, it will return you the whole data
object. 此外,如果你调用
$(this).data()
,它将返回整个data
对象。
Store them as data attributes on the radio buttons: 将它们作为数据属性存储在单选按钮上:
$(document).on('change', 'radioBtnName', function(e){
var $button = $(this);
var param1 = $button.data("param1");
var param2 = $button.data("param2");
// do whatever you want with the values :)
});
Note use document
instead of body
for delegated events. 注意使用
document
而不是委托事件的body
。 This avoids the need for a DOM ready handler (and avoids a bug with body
) 这避免了对DOM就绪处理程序的需求(并避免了
body
错误)
If I got you right you want to pass extra parameters with the .on()
method. 如果我说得对,你想用
.on()
方法传递额外的参数。 I hope the following example helps you. 我希望以下示例可以帮助您。
$(document).on('change', '#radioBlock input[type="radio"]', {param1: 'hell', param2: 'world'}, function(e){ console.log(e.data.param1); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="radioBlock"> <input type="radio" id="one" name="one" value="One"> <input type="radio" id="two" name="two" value="Two"> <input type="radio" id="three" name="three" value="Three"> </div>
You can use $(this).data()
like this: 您可以像这样使用
$(this).data()
:
$(function() { $("body").on('click', "#radioBlock input[type='radio']", function(e) { alert('Data Value - ' + $(this).data('value')); }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="radioBlock"> <label> <input type='radio' name='radio_input' data-value='1'> Radio 1 </label> <label> <input type='radio' name='radio_input' data-value='2'> Radio 2 </label> <label> <input type='radio' name='radio_input' data-value='3'> Radio 3 </label> </div>
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.