我有两个带有 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/