在页面加载时,通过标签名内联添加一个函数,如onmouseover

add a function by Tag Name inline like onmouseover when the page loads

本文关键字:一个 onmouseover 函数 添加 加载 标签名      更新时间:2023-09-26

我需要知道如何在标签内添加函数,这很重要,因为id和类是不同的,我需要应用具有相同标签名称的JavaScript方法。到目前为止,这是我想到的,我正试图让它工作。

<!DOCTYPE html>
<html>
<body onload="myFunction()">
<select>
    <option>1</option>
</select>
<br/>
<select>
    <option>1</option>
</select>
<script>
function myFunction()
{
    var elem = document.getElementsByTagName("SELECT");
    for (var i = 0;i < elem.length; i++)
    {
        elem[i].onmouseover = "this.style.background='red'";
    }
}
</script>
</body>
</html>

事件处理器是函数,所以:

elem[i].onmouseover = function() {
    this.style.background='red';
}

当您直接在HTML中添加事件处理程序时,例如在<div onmouseover="this.style.background='red'"></div>中,该包装器函数是隐式的。当从JavaScript附加处理程序时,它是强制性的,并且它的主体应该是常规代码,而不是字符串。

你可以试试这个

window.onload=function(){
    var elem = document.getElementsByTagName("SELECT");
    for (var i = 0;i < elem.length; i++)
    {
        elem[i].onmouseover = function(){ this.style.background='red'; }
        elem[i].onmouseout = function(){ this.style.background='white'; }
    }
};

演示。

您可以尝试这样做(包括在HTML中进行一些修复):

<!DOCTYPE html>
<html><head><title>Demo</title>
<script type='text/javascript'>//<![CDATA[ 
function highlight(){
    this.style.background='red';
}
window.onload=function(){
    var col = document.getElementsByTagName('select'), L=col.length;
    while(L--){ col[L].addEventListener("mouseover", highlight, false); }
};
//]]>  
</script>
</head><body>
<select>
    <option>1</option>
</select>
<br/>
<select>
    <option>1</option>
</select>
</body></html>

JSFiddle here.

如果你想要颜色切换,用这样的东西替换javascript:

function highlight(){
    var ts=this.style;
    ts.backgroundColor = ts.backgroundColor === 'red' ? '' : 'red';
}
window.onload=function(){
    var col = document.getElementsByTagName('select'), L=col.length;
    while(L--){ 
        col[L].addEventListener("mouseover", highlight, false); 
        col[L].addEventListener("mouseout", highlight, false);
    }
};