87,902
社区成员
发帖
与我相关
我的任务
分享
<select id="selectid" onchange="_f()">
<option value="a">a</a>
<option value="b">b</a>
</select>
<select id="selectid" >
<option value="a">a</a>
<option value="b">b</a>
</select>
<script>
document.getElementById("selectid").onchange=_f;
function _f()
{
alert("aaa");
}
</script>
During my development on SSIP i run into serveral problems with adding events dynamicly. After searching of an example implemetation i found this function
addEventListener(eventName, eventHandlerFunctionName, false);
Of corse there is an other one for ie:). Now i had the wish to pass parameters to the passed function. The approach i found looked like this:
addEventListener(eventName, function example(params){expression;}, false);
This meen we define the function directly in the addEventListenern an can then use local variables. But that was also not the solution i'm looking for. Ok then i taught i could directly write the function with the dynparameter on the tag with dom manipulation, something like this:
function addListener(element,type,expression){
element = getListenerElement(element);
if (navigator.appName.indexOf("Explorer") != -1){
expression = new Function(expression);
}
element.setAttribute(type, expression);
}
function getListenerElement(wichelement){
if(wichelement == 'body'){
element = document.getElementsByTagName("body")[0];
}else{
element = $(wichelement);
}
return element;
}
function $(element) {
if (typeof element == 'string'){
element = document.getElementById(element);
return element;
}
}
Now you can pass a function as String that will work on Firefox. With IE you have to pass a function object so it will work. But you don't have to care about, because this small addListener function will handle that.
The getListener Element just returns the handle element. It is not that smart, but fits my needs.
The $ function i look up by prototype. Its just for reducing the length of the code.
The only thing left is the remover function looking like this:
function removeListener(element,type){
element = getListenerElement(element);
element.setAttribute(type, '');
}
Thats the way it worked for me.