javascript - 如何将href自动设置为另一个div onclick函数href
问题描述
解决方案
如果我理解了你的问题,你可能想做这样的事情:
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 代码包装到一个函数中,以防万一您想多次重用它
推荐阅读
- node.js - fs.existsSync 不是 Nuxt JS + Lowdb 中的函数
- android - 刷新Android中的旧缓存数据
- php - 使用 laravel 控制主页内容的简单方法
- java - ParseError at [row,col]:[1,1] 消息:尝试从 JShare 获取文件时文件过早结束
- java - 有人可以解释如何使用日期对话框片段将数据发送回父片段吗?
- asp.net - 将文件导入项目的最佳方法
- python-2.7 - opencv2 NameError:未定义名称“输出”
- asp.net-core - 我想在 asp.net 核心 Web 应用程序中创建子区域
- c++ - c++函数重载,具体步骤是什么
- amazon-web-services - AWS 创建规则 AWS CLI 给出错误“条件 [0] 中的未知参数:“PathPatternConfig”,必须是以下之一:字段、值”