首页 > 解决方案 > 如何将href自动设置为另一个div onclick函数href

问题描述

标签: javascripthtmljqueryajaxonclick

解决方案


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

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 代码包装到一个函数中,以防万一您想多次重用它


推荐阅读