When the following statement is called when the page has not been loaded, the "add" object cannot be obtained, and the prompt is empty or not an object.
Copy the code code as follows:
document.getElementById("add").onclick = function(){
alert("hello");
}
objects that are available when used
Copy the code code as follows:
window.onload = function(){
document.getElementById("add").onclick = function(){
alert("hello");
}
}
Copy the code code as follows:
<script type="text/javascript">
//The selected item moves from the left to the right
function toright() {
var firstElement = document.getElementById("first");
var secondElement = document.getElementById("second");
var firstoptionElement = firstElement.getElementsByTagName("option");
var len = firstoptionElement.length;
for(var i=0;i<len;i++){
if(firstElement.selectedIndex != -1){ //selectedIndex is a property of select
secondElement.appendChild(firstoptionElement[firstElement.selectedIndex]);
}
}
}
//Move all to the right
function allright(){
var firstElement = document.getElementById("first");
var secondElement = document.getElementById("second");
var firstoptionElement = firstElement.getElementsByTagName("option");
var len = firstoptionElement.length;
for(var i=0;i<len;i++){
secondElement.appendChild(firstoptionElement[0]);//When the option option is selected, the index is 0
}
}
//Double click to move to the right
function db(){
/* //Method 1
var firstElement = document.getElementById("first");
var secondElement = document.getElementById("second");
var firstoptionElement = firstElement.getElementsByTagName("option");
var len = firstoptionElement.length;
for(var i=0;i<len;i++){
if(firstElement.selectedIndex != -1){ //selectedIndex is a property of select
secondElement.appendChild(firstoptionElement[firstElement.selectedIndex]);
}
} */
//Method 2
var firstElement = document.getElementById("first");
var secondElement = document.getElementById("second");
secondElement.appendChild(firstElement[firstElement.selectedIndex]);
}
</script>
<style type="text/css">
</style>
</head>
<body>
<table align="left">
<tr>
<td>
<select name="first" size="10" multiple="multiple" id="first" ondblclick="db()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
</td>
<td valign="middle">
<input id="add" name="add" type="button" value="---->" onclick="toright()"/>
<input id="add_all" name="add_all" type="button" value="==>" onclick="allright()"/>
</td>
<td align="left">
<select name="second" size="10" multiple="multiple" id="second">
<option value="Option 8">Option 8</option>
</select>
</td>
</tr>
</table>
</body>