Javascript 输入类型=“图像”的onClick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6585804/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:23:08  来源:igfitidea点击:

onClick with input type="image"

javascripthtml

提问by mitchellhislop

I have been going round and round trying to find a definitive answer. Basically, I want to add the Google Analytics event tracking to a form submit - I was hoping to add an onClick to it, but I am having a tough time finding out if all the browsers support it.

我一直在四处寻找一个明确的答案。基本上,我想将 Google Analytics 事件跟踪添加到表单提交中 - 我希望为其添加一个 onClick,但我很难确定是否所有浏览器都支持它。

I asked the person who designed the form, and she said that the reason they didn't use the button type is that is caused issues submitting the form in some browsers, but could not remember which ones.

我问了设计表单的人,她说他们没有使用按钮类型的原因是导致在某些浏览器中提交表单的问题,但不记得是哪些。

So, will it work across browsers, or should I switch to button?

那么,它可以跨浏览器工作,还是应该切换到按钮?

Relevant code below:

相关代码如下:

<input name="submit" id="submitme" type="image" 
  src="/graphics/creative/landing_pages/popup/ibd_signmeupbtn.gif" 
  alt="Sign Me Up!" 
  onClick="_gaq.push(['_trackEvent', 'Registrations', 'Register', 'Lightbox']);"
  tabindex="8"  />

EDITI have _gaq defined. The real goal of this question is to make sure that using an onClick with an input image is OK to do.

编辑我定义了 _gaq。这个问题的真正目标是确保对输入图像使用 onClick 是可以的。

回答by hunter

Try wiring it up a little different

尝试接线有点不同

<input name="submit" id="submitme" type="image" 
    src="/graphics/creative/landing_pages/popup/ibd_signmeupbtn.gif" 
    alt="Sign Me Up!" 
    onclick="SignMeUp();"
    tabindex="8"  />

And create your function like so:

并像这样创建你的函数:

<script type="text/javascript">
    function SignMeUp()
    {
        if (!!_gaq) // make sure _gaq is defined
            _gaq.push(['_trackEvent', 'Registrations', 'Register', 'Lightbox']);
    }
</script>

回答by developerdoug

you dont need to define the _gaq variable but you do need to import the google script.

您不需要定义 _gaq 变量,但确实需要导入 google 脚本。

here is an example of my code

这是我的代码示例

var _gaq = _gaq || [];
// i'm using asp.net web forms and getting google analytics code from config
_gaq.push(['_setAccount', '<%= ConfigurationManager.AppSettings["google.analytics.code"] %>']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();