简体   繁体   中英

How do I use JQuery to create an onclick javascript link in HTML with quote-including-string parameters?

I'm trying to create a link as follows in HTML:

<a href="javascript:void(0) onclick="print(string)">

I'm doing this using JQuery as follows:

html = '<a href="javascript:void(0)" onclick="print(\\'' + string + '\\')">'

However, I run into problems when string itself contains a single quotation mark. Is there any way that I can do something of this sort regardless of the characters contained in string ? The main ones I'm trying to figure out are both single and double quotation marks.

Best, and thanks for any advice,
Sami

I'm not sure if I understood your problem, but have you already tried the escape function?

Like this:

html = '<a href="javascript:void(0)" onclick="print(\'' + escape(string) + '\')">'

You could do this quite easily by simply encoding the string as a URIComponent before placing it in and then decoding it when you need it.

ie.

var NoQuotesString = encodeURIComponent(string);
//to encode the string without quotes

var BringBackMyQuotes = decodeURIComponent(NoQuotesString);
//decodes the string back to the original

Since your using jQuery why not use the event listeners it provides?

Give your link an id value:

<a href="#" id="someID">anchor</a>

Define the desired behavior with jQuery:

$('#someID').click(function(e) {
    e.preventDefault();// prevent the default anchor behavior
    $('#someID').text('New anchor text');// this is an example of the functionality
});

An example: http://jsfiddle.net/BfHrW/

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