简体   繁体   中英

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 :

<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.

I want the call to be by my input class and not by 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.

How to replace innerHTML of a div using jQuery?

$("#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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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