js动态给多个div添加跳转方法

如下的静态页面中,a标签跳转。但是这里会出现一个问题,只有点击到a标签内容时候,
才能发生跳转行为。

<div class="container" id="container" style=" margin-bottom: 160px;">
<div class="container-list">
    <a href="widget.html" style="text-decoration: none">
        <span>widget</span>
        <span style="float: right; opacity: 1;">
        <img src="../img/Index_ico_arrow_right.png">
        </span>
    </a>
</div>
<div class="container-list">
    <a href="shortcutOperation.html" style="text-decoration: none">
        <span>快捷操作</span>
        <span style="float: right; opacity: 1;">
        <img src="../img/Index_ico_arrow_right.png" >
        </span>
    </a>
</div>
<div class="container-list">
    <a href="physicalButton.html" style="text-decoration: none">
        <span>物理按键</span>
        <span style="float: right; opacity: 1;">
        <img src="../img/Index_ico_arrow_right.png" >
        </span>
    </a>
</div>
</div>

目前我的解决方法是,给class="container-list"添加一个click事件。在html里面写死的函数跳转,内容量小可以的。但是如果要大代码量,会变得异常繁琐。

获取class="container-list"的列表,然后插入onclick函数。
window.onload = function () {
    var elements = document.getElementsByClassName("container-list");
    for(var i=0; i<elements.length; i++) {
        var obj = elements[i];
        obj.setAttribute("onclick", "sendUrl(this)");
    }
};
在当前页面中添加sendUrl函数就可以了
function sendUrl(obj) {
    try {
        var url = obj.getElementsByTagName("a")[0].href;
        if(url) {
            window.location.href = url;
        }
    } catch (ex) {
    }
}

为了提高js函数的可靠性,添加了try-catch机制。

鉴于水平有限,可能存在错误,希望不吝指出 email: [email protected]

猜你喜欢

转载自blog.csdn.net/Hello_Ray/article/details/83615544
今日推荐