简体   繁体   English

Javascript:将内联代码注入html标签

[英]Javascript : Inject inline code to a html tag

I would like to add my Google Analytics tracking event code inline to my input html tag : 我想将我的Google Analytics(分析)跟踪事件代码内联添加到我的输入 html标签中:

<input class="addtobag">

to have something 有东西

<input class="addtobag" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">

I'm asking this as I don't have access to the file that contains the tag so I'm unable to make the change manually so I'm looking for a javascript code that I will put in the head so when that page load, the tracking event code would be injected automatically. 我问这个问题是因为我无权访问包含标记的文件,所以我无法手动进行更改,因此我正在寻找将放在头部的javascript代码,以便在加载该页面时,跟踪事件代码将自动注入。

I want the call to be by my input class and not by id . 我希望调用是通过输入类而不是id进行的

Why do you want to do it inline? 为什么要内联?

document.getElementById('ctl00_mainContentPlaceHolder_lvLookProducts_ctrl0_buyArea3493_btnAddToCart').onclick = function () {
    _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
};

To do it by class name, you'll need to do a little more logic: 要按类名进行操作,您需要做更多的逻辑:

var inputs = document.getElementsByClassName('AddToBag'),
    i = inputs.length;

while(i--) {
    inputs[i].onclick = function () {
        _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
    }; 
}

Fetching by class name returns a list, so you'll have to loop through to apply the handler. 按类名获取将返回一个列表,因此您必须循环遍历以应用处理程序。

jQuery is your friend. jQuery是您的朋友。

How to replace innerHTML of a div using jQuery? 如何使用jQuery替换div的innerHTML?

$("#regTitle").html("Hello World");

EDIT 编辑

Guess I didn't read this one, but still same principle. 猜猜我没有读过这个,但还是一样的原理。

$(".addtobag").click(_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']));

http://api.jquery.com/click/ http://api.jquery.com/click/

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

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