用于li标记onclick位置的Javascript

时间:2014-05-15 05:29:30

标签: javascript

li tag onclick的Javascript代码,

使用下面的代码,但无法覆盖范围标记onclick。

HTML:

<div class="primaryNav fl">

 <ul id="hd_vertical" class="productNav">

    <li id="info" class="validation">
    <span class="info">Test</span>
    <a class="info" href="http://validator.w3.org/">Test1</a>
    </li>

    <li id="learn" class="site">
    <span class="learn">fi</span>
    <a class="learn" href="http://www.w3schools.com/">Buses</a>
    </li>

  </ul>
</div>

JS:

document.getElementById("hd_vertical").addEventListener("click",function(e) {
    if(e.target && e.target.nodeName == "LI") {
        var _anchor = e.target.id;
        var _url = document.getElementsByClassName(_anchor)[1].getAttribute('href');
        location.href = _url;
    }
});

jsfiddle:

http://jsfiddle.net/sudheera/NgwS5/

我有li标签onclick的jquery代码,我尝试在Javascript中做同样的事情。

请建议我!!

3 个答案:

答案 0 :(得分:1)

由于您的检查仅针对LI编写,因此不会在if语句中包含其他标记。你也必须处理另一个。所以对于SPAN标记,您可以这样做:

var changeLocation = function(id) {
  var _url = document.getElementsByClassName(id)[1].getAttribute('href');
  location.href = _url;   
}

document.getElementById("hd_vertical").addEventListener("click",function(e) {
    var _anchor = ""; 
    if(e.target) {
        // checc which tag is clicked.
        alert("tag is :" + e.target.nodeName);

        if(e.target.nodeName == "LI") { 
            _anchor = e.target.id;
            changeLocation(_anchor);
        } else if(e.target.nodeName == "SPAN") {
            _anchor = e.target.className;   
            changeLocation(_anchor);
        }
    }
});

Jsfiddle:span-tag-working

答案 1 :(得分:1)

试试这个

document.getElementById("hd_vertical").addEventListener("click",function(e) {
    if(e.target && e.target.className) {
        var _anchor = e.target.className;
        var _url = document.getElementsByClassName(_anchor)[1].getAttribute('href');
        location.href = _url;
    } 
});

JS Fiddle

答案 2 :(得分:1)

您可以找到parentNode并获得所需的功能

,而不是上课

Demo Fiddle

Javascript

document.getElementById("hd_vertical").addEventListener("click",function(e) {
        if(e.target.nodeName == "LI") { 
            var _anchor = e.target.id;
            changeLocation(_anchor);
        } else if(e.target.nodeName == "SPAN") {
            var span = e.target;
            var li = span.parentNode;
            var _anchor = li.id;   
            changeLocation(_anchor);
    }
});  

Same answer at
希望它有所帮助......