JS Click event callback function to pass the parameters of the data structure

Source: Internet
Author: User
Click the event callback function to pass the argument using anonymous functions
function Testfun (event, str) {
	console.log (str);
}

var test = document.getElementById (' test ');
Test.addeventlistener (' click ', Function (event) {
	Testfun (event, ' is a test ');
};

When the example above gives the element a point-and-click event function, use the anonymous function, in the anonymous function and then call the Testfun function, so that you can easily pass the parameters to the Testfun function, but this method looks so silly, the most fatal is not to the element to bind Click event Processing function, is really the worst.
using the Bind method
function Testfun (str, event) {
	console.log (str);
	Console.log (Event.target = = this);
}

var test = document.getElementById (' test ');
Test.addeventlistener (' Click ', Testfun.bind (test, ' is a test ');

In the example above, the Bind method is used to assign the this value and parameters to the Testfun function, which can also achieve the effect of passing parameters to the callback function, which looks more elegant. It is worth noting, however, that the last parameter of the callback function is the event object. At the same time, this method still cannot bind the event handler and is not supported under IE9.
jquery Method
function Testfun (event, str) {
	console.log (EVENT.DATA.STR);
	$ (this). Unbind (' click ', Testfun);
}

$ (' #test '). Click ({str: ' This is a test '}, Testfun);

The above is a method of using jquery, and note that if the Click event does not pass in the first argument, it is treated as a mock click event. This method treats the first parameter of click as a data property of the event object, which can be used to pass parameters in the incident handler function, most notably through the Unbind method of jquery itself to bind the event handler.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.