简体   繁体   中英

Appending the javascript onclick event to anchor tag

Im trying to append the onclick event to my Phonegap Application. Where it will link to external browser.

My Code:

pair +='<div class="card_background" style="background-image: url("http://placehold.it/600x200");" valign="bottom" class="card-header color-white no-border"><div class="card_overlay"></div><div class="animated_background"></div><h3 class="card-title">'+ results.rows.item(i).title +'</h3></div><div class="card-content"><div class="card-content-inner"><p class="color-gray event_details">Event Location:  <strong>'+ results.rows.item(i).eventlocation +'</strong></p><p class="color-gray event_details">Event Date: <strong>'+ date + " " + month + " " + year +'</strong></p><a href="#" onclick="window.open("'+ results.rows.item(i).eventOrganiserLink +'", _system, location=yes);">Google</a><br/></div></div>';

inside loop, Later I append it to div

Im trying to add :

<a href="#" onclick="window.open("'+ results.rows.item(i).eventOrganiserLink +'", _system, location=yes);">Google</a>

It gives me error

Thanx in advance

I've simplified your code somewhat. Consider the following:

var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';

pair += '<a href="#" onclick="window.open("'+ eventOrganiserLink +'", _system, location=yes);">Google</a>';

This would generate the following:

<a href="#" onclick="window.open("[EVENT ORGANISER LINK]", _system, location=yes);">Google</a>

The onclick attribute opens with double quote ("), which means it will look for the first double quote after that to close it. That's right after window.open( meaning that part is the only thing that will be set as the onclick attribute. See how the colors in the onclick attribute in the code box here at StackOverflow don't really match up?

It is a little tricky because we're mixing quotes (setting the pair variable) and double quotes (as text inside that variable, which will be used as html later on - so it needs to be valid).

You can use single quotes for the first window.open parameter and escape them in the assignment to your pair variable, like so:

var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';

pair += '<a href="#" onclick="window.open(\''+ eventOrganiserLink +'\', _system, location=yes);">Google</a>';

This would yield:

<a href="#" onclick="window.open('[EVENT ORGANISER LINK]', _system, location=yes);">Google</a>

Note the single quotes around [EVENT ORGANISER LINK] . Also note the colors now match up.

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