从父锚到Div获取链接

时间:2013-06-13 01:11:11

标签: javascript html hyperlink onclick

如何将div的onClick href设置为我的父锚点href值?

<a href="getThisLink.html" target="_parent">
    <img src="images/1.jpg" />
    <span>
    <div onclick="parent.location.href='**Link me with my anchor parent**' + 'params1';" >
           <span>Words Words Words</span>
    </div>            
</span>
</a>

注意我在幻灯片中使用它。

2 个答案:

答案 0 :(得分:2)

下面的函数updateHref()采用div元素并查找父元素的父标记。并且()如果它是锚(<a>)标记:

  • 点击div 会将页面转到 <a>的href加上urlParams
  • <a> href现在将转到旧网址加上urlParams

Demo link here。代码如下:

function updateHref(divElement, urlParams) {
    var parentAnchor = divElement.parentNode.parentNode;
    if (parentAnchor.nodeName != "A") return;
    var url = parentAnchor.href + urlParams;
    divElement.onclick = function() {
        parent.location.href = url;
    }
    parentAnchor.href = url; // override parent anchor href URL
}

用法:

// for a specific div
var myDiv = document.getElementById('myDiv');
updateHref(myDiv, "search?p=param1");

// for all divs of the page (whose parent's parent is an anchor tag)
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
    updateHref(divs[i], "search?p=param1");    
}

答案 1 :(得分:0)

您的代码无效,但是,这是工作脚本:

<a href="getThisLink.html" target="_parent">
    <img src="images/1.jpg" />
    <span>
        <div onclick="location.href = this.parentNode.parentNode.href + '#param1'; return false;">
            <span>Words Words Words</span>
        </div>
    </span>
</a>