繁体   English   中英

在Javascript函数中模拟href点击?

[英]Simulate the href click in Javascript function?

我在jsp的遗留项目中有以下代码:

<tr>
    <th colspan="2">Customer</th>
    <td colspan="2">
      <a href="myAction.do" target="view">CustomerLink</a></td>
</tr>

当我们单击 CustomerLink 时,我希望对行为进行一些修改。 我只想在点击操作之前在 Javascript 函数中做一些处理。 我不知道如何在 Javascript 函数中模拟 href 链接行为?

我试过的:-

<tr>
    <th colspan="2">Customer</th>
    <td colspan="2">
      <a href="javascript:customerLinkClicked('myAction.do')" target="view">CustomerLink</a></td>
</tr>

// Javascript 函数

function customerLinkClicked(path)
{

    // simulate the href link behaviour, not sure how to do this


}
<a href="javascript:customerLinkClicked('myAction.do')" target="view">CustomerLink</a>
<script>
    function customerLinkClicked(path) {
        if (confirm('message'))
            document.location.href = path;
    }
</script>

您可以使用window.confirm获取确认对话框,根据选择返回 true 或 false。 之后,可以通过event.preventDefault方法取消默认行为。

示例: http : //jsfiddle.net/Klaster_1/nXtvF/

$("a").on("click", function(event) {
    if(!window.confirm("Proceed?")){
        event.preventDefault()
    };
});

我在其中使用了 jQuery,但它完全是可选的。

关于什么:

<a href="myAction.do" onclick="customerLinkClicked()" target="view">CustomerLink</a>

首先会处理onclick 事件处理程序,然后将位置更改为myAction.do。

如果你想防止改变位置,你可以写

onclick="return customerLinkClicked();"

根据返回值(true、false),位置会发生变化。 或不。

试试这个。只需复制和粘贴

<script type="text/javascript">
function fnc()
{
if(confirm("Do you really want to go?"))
{window.open("yoursitename.do");}
}
</script
<a href="javascript:fnc()">click</a>

您应该避免内联 js,但对于您当前的情况。

    function customerLinkClicked(event) {
        if(!confirm("Are you sure ?")) {
              if(event.preventDefault) {
                  event.preventDefault();
              }
              else {
                   event.returnValue = false;
              } 
        } 
    }

HTML

<a href="myAction.do" onclick="customerLinkClicked(event);" target="view">CustomerLink</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM