使用e.target可以確定知道所選擇的元素是否是自己需要的。
//HTML
<body>
<ul>
<li><a href="#">123</a></li>
</ul>
</body>
//Javascript
var el = document.querySelector('html');
el.addEventListener('click',function(e){
e.preventDefault();
console.log(e.target.nodeName);
})
<ul><li><a href="#">123</a></li></ul>
來試驗 e.target
功用html
標籤e.preventDefault()
取消瀏覽器的預設行為console.log(e.target.nodeName)
來顯示點擊到哪個元素,nodeName
是節點名稱練習使用下拉式選單select,選擇不同選項,顯示不同的內容 :
<body>
<select id="sportId">
<option value="路跑">路跑</option>
<option value="騎車">騎車</option>
</select>
<ul class="sportlist"></ul>
</body>
var sport = document.getElementById('sportId');
var sportlist = document.querySelector('.sportlist');
var motion = [
{
sportType: '路跑',
sportplace: '田徑場'
},
{
sportType: '路跑',
sportplace: '操場'
}
,{
sportType: '騎車',
sportplace: '河濱'
}
]
var len = motion.length;
e.target.value
來確認當前選項的值innerHTML
插入UL.sportlist裡sportlist.innerHTML = str;
function updateSport(e){
var select = e.target.value;
var str='';
for(var i=0;len>i;i++){
if(select== motion[i].sportType){
str += '<li>'+motion[i].sportplace+'</li>'
}
}
sportlist.innerHTML = str;
}
sport.addEventListener('change',updateSport,false)
練習結果
附上JS
var sport = document.getElementById('sportId');
var sportlist = document.querySelector('.sportlist');
var motion = [
{
sportType: '路跑',
sportplace: '田徑場'
},
{
sportType: '路跑',
sportplace: '操場'
}
,{
sportType: '騎車',
sportplace: '河濱'
}
]
var len = motion.length;
function updateSport(e){
var select = e.target.value;
var str='';
for(var i=0;len>i;i++){
if(select== motion[i].sportType){
str += '<li>'+motion[i].sportplace+'</li>'
}
}
sportlist.innerHTML = str;
}
sport.addEventListener('change',updateSport,false)