设置属性功能,但不运行它 [英] Set attribute to a function, but don't run it
问题描述
考虑下面的一块jQuery的code的。这将根据用户选择的几个单选按钮的变种,它增加了该选择的URL的值。然后,URL被设置为一个按钮的数据单击属性。
Consider the below piece of jQuery code. It sets a var based on the users selection of a few radiobuttons, it adds the value of that selection to the URL. Then, that url is set to the data-click attribute of a button.
这一切工作正常,如果不是因为该功能setcheckoutLocation似乎对单选按钮的选择引发的事实。
我预计jQuery的ATTR code设置属性为选定的元素,而不是立即运行。它只需要按钮本身(#directcheckoutbutton)被点击时运行。
This all works fine, if it wasn't for the fact that the function setcheckoutLocation seems to be triggered on the selection of the radiobutton. I expected the jQuery attr code to set the attribute for the selected element, not immediately run it. It only needs to run when the button itself (#directcheckoutbutton) is clicked.
jQuery(document).ready(function() {
jQuery('input').on('change', function() { // On choice selection
var productcode = jQuery('input:checked', '#product-options-wrapper').val(); // Get chosen value code
var quickbuyurl = '<?php echo $_directcheckout; ?>'+productcode; // Add code to end of url
jQuery('#directcheckoutbutton').attr('data-click', setcheckoutLocation(quickbuyurl)); // Set url as onClick for button
});
});
我图也许调用这样的函数的方式使浏览器读取它作为一个执行的功能,而不是一个(比方说)一个它需要附加到属性字符串。
但我似乎无法弄清楚,我试图设定的功能在一个单独的VAR作为一个字符串,并追加这一点,但它不工作。
I'd figure maybe the way of calling the function in this way causes the browser to read it as a executable function, rather then a (say) a string it needs to append to the attribute. But I can't seem to figure it out, I've tried to set the function in a seperate var as a string, and appending that, but it doesn't work.
推荐答案
试试这个。
jQuery(document).ready(function() {
jQuery('input').on('change', function() { // On choice selection
var productcode = jQuery('input:checked', '#product-options-wrapper').val(); // Get chosen value code
var quickbuyurl = '<?php echo $_directcheckout; ?>'+productcode; // Add code to end of url
jQuery('#directcheckoutbutton').attr('data-click', quickbuyurl); // Set url as onClick for button
});
});
然后使用功能上点击:
and then use the function on click:
jQuery('#directcheckoutbutton').on("click", function() {
setcheckoutLocation($(this).attr('data-click'));
});
这假定你总是使用相同的功能 setcheckoutLocation()
This assumes you're always using the same function setcheckoutLocation()
修改
您也可以跳过输入
code,只是处理它的点击函数中:
You could also skip the input
code and just handle it inside the click function:
jQuery('#directcheckoutbutton').on("click", function() {
var productcode = jQuery('input:checked', '#product-options-wrapper').val(); // Get chosen value code
var quickbuyurl = '<?php echo $_directcheckout; ?>'+productcode; // Add code to end of url
setcheckoutLocation(quickbuyurl);
});
这篇关于设置属性功能,但不运行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!