我想在用户关注select元素时触发一个事件。我不能编辑正文代码。因此,我试图通过head oly中的JS来实现它。如果我可以在我的select元素中添加属性,即使是在header标签中的Javascript,这也是很有意义的。
我希望当用户单击选择元素时显示警报。帮助。
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
if(document.getElementByd("t2").focus)
{
alert("hello");
}
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm">
t1: <input type="text" id="t1" name="t1"/>
t2: <select id="t2">
<option></option>
<option>1</option>
<option>2</option>
</select>
t3: <input type="text" id="t3" name="t3"/>
</form>
</body>
</html>
发布于 2014-02-26 06:27:24
试试这个:
document.getElementById("t2").setAttribute("onclick", "alert()");
发布于 2014-02-26 06:36:29
尝试以下代码
var att=document.createAttribute("onclick");
att.value="yourFunction()";
document.getElementById("t2").setAttributeNode(att);
function yourFunction(){
// your js code
}
发布于 2014-02-26 06:45:18
使用此选项,当选择框获得焦点时,将出现警告消息
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
if(document.getElementById("t2").focus)
{
alert("hello");
}
document.getElementById("t2").setAttribute("onfocus", "selectHiglight()");
}
var selectHiglight=function(){
alert('select get hilghited');
};
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm">
t1: <input type="text" id="t1" name="t1"/>
t2: <select id="t2">
<option></option>
<option>1</option>
<option>2</option>
</select>
t3: <input type="text" id="t3" name="t3"/>
</form>
</body>
</html>
https://stackoverflow.com/questions/22033396
复制