如何将< a>href自动设置为另一个div onclick函数href

osh3o9ms  于 2021-09-23  发布在  Java
关注(0)|答案(4)|浏览(277)

我有一个这样的部门:

<div onclick="location.href='';" style="cursor: pointer;">
    <div class="item">   
        <a href="example" class="btn">Buy</a>                
    </div>  
</div>

我想自动分配 href 属于 <a> 设置为 examplehref onclick函数的定义: <div onclick="location.href='';" style="cursor: pointer;"> 那么如何做到这一点呢?
我非常感谢你们的任何想法或建议。。。
提前谢谢。

iibxawm4

iibxawm41#

javascript将是这样的

function setLocation(divObj) {
            var anchorTag = divObj.getElementsByTagName("a")[0];

            console.log(anchorTag);

            window.location.href = anchorTag.href;
        }

而html将是

<div onclick="setLocation(this);" style="cursor: pointer;">
        <div class="item">
            <a href="example" class="btn">Buy</a>
        </div>
</div>
vcirk6k6

vcirk6k62#

您可以通过向div添加事件侦听器并修改事件中的a标记来实现这一点。
注意 ev.target 实际上是指 <a> 标记自身,而不是 <div> .

<div id="buy-div" style="cursor: pointer;">
    <div class="item">   
        <a class="btn" href="example">Buy</a>                
    </div>  
</div>
const buyDivEl = document.getElementById('buy-div');
buyDivEl.addEventListener('click', ev => {
    ev.target.href = '';
});
dfty9e19

dfty9e193#

您可以为任何div创建一个类,该div应该继承其中锚定链接的href并循环通过它们,创建侦听器并获取href。

window.addEventListener('load', () => {
  document.querySelectorAll('.inheritor').forEach(el => {
    el.addEventListener('click', e => {
      window.location.href = e.target.querySelector('a').getAttribute('href');
    })
  })
})
.inheritor {
  cursor: pointer;
  padding: 15px;
  background: #f0f0f0;
}
<div class='inheritor'>
  <div class="item">
    <a href="example" class="btn">Buy</a>
  </div>
</div>
nmpmafwu

nmpmafwu4#

如果我理解了你的问题,你可能想这样做:

const myDiv = document.getElementById("myDivId");

const prevOnClickAttr =  myDiv.getAttribute("onclick")
// formatting in order to insert the anchors attribute inside the string value more easly
.split("=")[0]+"='";

console.log("previous onclick: ", myDiv.getAttribute("onclick"));

const onClickToAdd = myDiv.getElementsByTagName("a")[0].getAttribute("href")
// closing the string value here
+"';";

myDiv.setAttribute( "onclick", prevOnClickAttr + onClickToAdd );

console.log("new onclick div's attribute: ",myDiv.getAttribute("onclick"));
<div id="myDivId" onclick="location.href='';" style="cursor: pointer;">
    <div class="item">   
        <a href="#myDivId" class="btn">Buy</a>                
    </div>  
</div>

当然,您可能更喜欢将javascript代码 Package 到函数中,以防您想多次重用它

相关问题