简体   繁体   English

锚链接功能 - onclick和href

[英]Anchor link function - onclick and href

I have anchor link with onclick and href functions. 我有onclick和href函数的锚点链接。 like below code 像下面的代码

$("div.actions").append('<a id="excelExport" onClick="callajax();" class="actionButton" alt="Export to Excel" title="Export to Excel" href="partexport" ></a>')

function callajax() {
     jQuery.ajax({
     url : '<s:url action="partexport"/>',
     data : "fters.productNbr" : $("#productsTextArea1").val()} });

     }

Callajax is not at all calling when click the anchor link. 点击锚链接时,Callajax根本没有打电话。

The click handler will fire first. click处理程序将首先触发。 Depending on how to process your click, you can control whether the href link action goes through or not. 根据处理点击的方式,您可以控制href链接操作是否通过。

You can do both - ie have your click handler as well as the link action to go through. 您可以同时执行这两项操作 - 即让您的点击处理程序以及链接操作完成。 All you need to do is not return false or call event.preventDefault() from your click handler. 您需要做的就是不return false或从Click处理程序调用event.preventDefault()

There are a coulple things at play here. 这里有一些可以玩的东西。

  1. if you are using jquery already it is best to use jquery to attach the handler. 如果你已经使用jquery,最好使用jquery来附加处理程序。 Given this is an injected link it is tricky but my example covers how to do that. 鉴于这是一个注入链接,它是棘手的,但我的例子涵盖了如何做到这一点。
  2. Your semi-colon is outside of the quotation marks for the onClick handler 您的分号位于onClick处理程序的引号之外
  3. To avoid the default behavior of an anchor tag, all e.preventDefault(). 为了避免锚标记的默认行为,所有e.preventDefault()。 This one isn't as big of a deal in your case as you dont redirect to an actual location but you might see odd behavior if you dont explicitly say 'dont do the default behavior' 在你的情况下,这个并不像你没有重定向到实际位置那样大,但如果你没有明确说'不做默认行为',你可能会看到奇怪的行为

http://jsfiddle.net/g30rg3/u5k95/3/ http://jsfiddle.net/g30rg3/u5k95/3/

$(document).ready(function(){
    $("div.actions").append('<a id="excelExport" class="actionButton" alt="Export to Excel" title="Export to Excel" href="http://www.stackoverflow.com">click me</a>');
    $('div.actions').on('click.mylink', '#excelExport',function(e){
        e.preventDefault();
        callajax();
    });

});

function callajax() {
    alert('clicked');

}

The click event will be executed first and then depending on the result, the href will be executed. 将首先执行click事件,然后根据结果执行href。 For example returning false from the click event will prevent the href from being executed. 例如,从click事件返回false将阻止href被执行。

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

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