Home >Web Front-end >JS Tutorial >Two useful Javascript tool function codes_javascript skills

Two useful Javascript tool function codes_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:34:24893browse
1. In actual work, everyone will write a variety of assignment statements.
For example, the most commonly used obj.style.display = "none";
If there are too many assignment statements like this, obj.style will be dizzy after being laid out in a row

Next I will The extend function in base.js allows you to assign attributes and even function handles in json format
Copy code The code is as follows:

/**
* Extension function
* @param target The object that needs to be extended
* @param params The attributes and methods to be put into the target
*/
function extend(target, params) {
if (!target) {
target = {};
}
for (var prop in params) {
    target[prop] = params[prop];
  }
  return target;
}

2. Since IE does not fully comply with w3c standards, and its event model is different from other browsers. The calling methods are also different.
If you encounter the need to dynamically add events to the control. Using onclick = function() {} may not be effective when the dom is dynamically created, and multiple handles cannot be bound. The following introduces a general binding event function that supports all browsers.
In most cases, useCapture is false, so just write it to death here.
Copy code The code is as follows:

/**
* Dynamically create event handle
* @param control object that needs to be extended
* @param eventName event name
* @param fn function handle
*/
function addEventListener(control, eventName, fn) {

if (window.attachEvent) {
control.attachEvent('on' eventName, fn);
} else {
control.addEventListener( eventName, fn, false);
}
}

For the usage sample of the above two functions, you can refer to the code in other articles I wrote
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn