javascript - 如何将 'this' 与 onClick 结合使用以从正确的 href 获取属性

标签 javascript html

我有两个带有 href 的表单用于发布它们,但只有一个 onClick 函数。我希望 javascript 函数知道哪个 href 已被单击,但无法真正让 this 工作。应该是一个简单的任务,但我对 javascript 很陌生!如果有人能解释我应该如何在这种情况下使用 this ,将会很有帮助。

代码:

function sendComment(){
	document.getElementById(this.getAttribute('data-id')).submit();
}
<form id="submitComment1" action="<%= addComment %>" method="post" enctype="multipart/form-data" >
   <aui:input style="width:95%;" type="text" value="<%=content%>" name="Content"></aui:input>
   <a href='' id="sc1" data-id="submitComment1" onClick="sendComment()">Comment</a>
</form>

<form id="submitComment2" action="<%= addComment %>" method="post"   enctype="multipart/form-data" >
   <aui:input style="width:95%;" type="text" value="<%=content%>" name="Content"></aui:input>
   <a href='' id="sc2" data-id="submitComment2" onClick="sendComment()">Comment</a>
</form>

最佳答案

您需要将this作为参数传递。

onClick="sendComment(this)"//Pass this as argument


function sendComment(ele){
    document.getElementById(ele.getAttribute('data-id')).submit();
}

关于javascript - 如何将 'this' 与 onClick 结合使用以从正确的 href 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30483041/

相关文章:

javascript - 应用 z-index 时悬停状态不起作用

javascript - 使 JS 幻灯片的第一张幻灯片持续时间更长

html - 从字符串中剥离 HTML

javascript - Bootstrap Carousel 更改特定颜色的 div

html - 将鼠标悬停在 <li> 上更改 div 大小

javascript - Facebook iFrame JavaScript SDK - 不带 OAuth

javascript - 如何使用 KineticJS 限制图像拖动?

javascript - 自动完成时的空密码输入值 (React.js)

javascript - 单击隐藏按钮以显示通知文本,然后 5 秒后再次隐藏文本并重新显示按钮

html - 使用 Ruby Mechanize 解析结构不良的 HTML 文档