1. 程式人生 > >js動態給多個div新增跳轉方法

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機制。