Javascript 在超链接的点击事件上调用javascript函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14020355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call javascript function on the click event of hyperlink
提问by Bhushan
I am developing a web application using JSP and Servlet.
我正在使用 JSP 和 Servlet 开发 Web 应用程序。
I am trying to call javascript function on the click event of hyperlink, and with that I am also passing some parameters to servlet using query string.
我试图在超链接的点击事件上调用 javascript 函数,并且我还使用查询字符串将一些参数传递给 servlet。
<td> <a href="#?id=<%=data[i][0]%>&protID=<%=data[i][1]%>&seqNo=<%=data[i][2]%>" onclick="getValues();" >Edit</a></td>
javascript function:
javascript函数:
<script>
function getValues()
{
var url = document.URL;
var planID = url.split("=");
var pID = planID[1].split("&");
var remURI = url.split("&");
var protID = remURI[1].split("=");
var s = remURI[2].split("=");
document.getElementById('txtPlanID').value=pID[0];
document.getElementById('txtProtID').value=protID[1];
document.getElementById('txtSeqNo').value=s[1];
//show("block");
return false;
}
</script>
But the problem is that I have to click twice on hyperlink to get desired result. I think onClick event is executing before sending query string. Please let me know if there is anything wrong in source code.
但问题是我必须在超链接上单击两次才能获得所需的结果。我认为 onClick 事件在发送查询字符串之前正在执行。请让我知道源代码中是否有任何错误。
Thanks in advance.....
提前致谢.....
回答by Nipun Jain
<td> <a href="#" onclick="getValues('<%=data[i][0]%>','<%=data[i][1]%>','<%=data[i][2]%>');" >Edit</a></td>
function getValues(pID,protID,eq)
{
document.getElementById('txtPlanID').value=pID;
document.getElementById('txtProtID').value=protID;
document.getElementById('txtSeqNo').value=eq;
//show("block");
return false;
}
}
simply pass values while calling javascript get use it
只需在调用 javascript 时传递值即可使用它
回答by pala?н
Try this:
尝试这个:
<a href="javascript:return getValues('<%=data[i][0]%>','<%=data[i][1]%>','<%=data[i][2]%>');">Edit</a>
JS
JS
function getValues(value1, value2, value3)
{
document.getElementById('txtPlanID').value = value1;
document.getElementById('txtProtID').value= value2;
document.getElementById('txtSeqNo').value= value3;
return false;
}
回答by Dr.Molle
Provide the clicked link as argument to the function:
提供点击的链接作为函数的参数:
onclick="getValues(this);return false;"
then use the href-attribute of the link as url:
然后使用链接的 href 属性作为 url:
function getValues(link)
{
var url = link.href;
//more code
}

