I'm trying to fire up event handling based on the listindex of a DOM element. I can't quite figure why the code doesn't work as I'm running it in a bootstrap environment.
Javascript:
window.onload = function(){
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
var ul = document.getElementById("aloga");
ul.onclick = function(event) {
var target = getEventTarget(event);
var bman = getElementsByTagName("option")
if (target.selectedIndex == "0") {
window.alert("Hello Peter")
} else if (target.selectedIndex == "1") {
window.alert("Hello Paul")
} else {
window.alert("Hello Penn")
}
};
}
Then here is the HTML code below:
<select name="aloga" data-placeholder="Select your aloga" id="aloga" class="form-control input-lg select2">
<option value="1" data-code="A" selected > Peter </option>
<option value="2" data-code="B"> Paul </option>
<option value="3" data-code="C"> Penn </option>
</select>
将getElementsByTagName("option")
更改为document.getElementsByTagName("option")
replace your javascript code with this.
document.getElementById("aloga").onchange = function(){
var index = this.selectedIndex;
var name = this.options[index].text;
window.alert("Hello "+name);
}
jsFiddle link https://jsfiddle.net/ueyorfej/
I agree with brk's comment but still if that doesn't work then i am pasting my working code for reference
Note: I have embedded your code in a fucntion attachEvents() also modified the
var bman = getElementsByTagName("option") to var bman = document.getElementsByTagName("option") as below
<html>
<script>
function attachEvents(){
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
var ul = document.getElementById("aloga");
ul.onclick = function(event) {
var target = getEventTarget(event);
var bman = document.getElementsByTagName("option")
if (target.selectedIndex == "0") {
window.alert("Hello Peter")
} else if (target.selectedIndex == "1") {
window.alert("Hello Paul")
} else {
window.alert("Hello Penn")
}
};
}
</script>
Then here is the HTML code below:
<body onload="attachEvents()">
<select name="aloga" data-placeholder="Select your aloga" id="aloga" class="form-control input-lg select2">
<option value="1" data-code="A" selected > Peter </option>
<option value="2" data-code="B"> Paul </option>
<option value="3" data-code="C"> Penn </option>
</select>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.