如何使用JQuery在HTML中创建包含字符串参数的引号的onclickjavascript链接

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

本文关键字:参数 链接 onclickjavascript 字符串 包含 JQuery 何使用 HTML 创建      更新时间:2023-09-26

我正在尝试在HTML:中创建如下链接

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

我使用JQuery如下所示:

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

然而,当string本身包含一个单引号时,我遇到了问题。不管string中包含什么字符,我有什么方法可以做这种事情吗?我想弄清楚的主要是单引号和双引号。

最好的,谢谢你的建议,
萨米语

您可以很容易地做到这一点,只需在放入字符串之前将其编码为URIComponent,然后在需要时对其进行解码。

即。

var NoQuotesString = encodeURIComponent(string);
//to encode the string without quotes
var BringBackMyQuotes = decodeURIComponent(NoQuotesString);
//decodes the string back to the original

我不确定我是否理解你的问题,但你已经尝试过escape函数了吗?

像这样:

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

既然使用jQuery,为什么不使用它提供的事件侦听器?

给你的链接一个id值:

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

使用jQuery:定义所需的行为

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

例如:http://jsfiddle.net/BfHrW/