最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Passing double quotes to Jscript - Stack Overflow

programmeradmin1浏览0评论

insertText is java script that accepts two string paramters

I need to pass two strings

first parameter:

<img src="

second

 ">

I just cant figure out how to pass double quote as parameter

This works

<a onClick="insertText('<em>', '</em>'); return false;">Italic</a>

This does not

<a onClick="insertText('<img src=/"', '/">'); return false;">Image</a>

Prints '); return false;">Image

insertText is java script that accepts two string paramters

I need to pass two strings

first parameter:

<img src="

second

 ">

I just cant figure out how to pass double quote as parameter

This works

<a onClick="insertText('<em>', '</em>'); return false;">Italic</a>

This does not

<a onClick="insertText('<img src=/"', '/">'); return false;">Image</a>

Prints '); return false;">Image

Share Improve this question edited Feb 23, 2011 at 9:38 Phil Helix 3,7334 gold badges31 silver badges52 bronze badges asked Feb 23, 2011 at 9:35 Captain ComicCaptain Comic 16.2k45 gold badges114 silver badges152 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

You want to use \ rather than /

The escape character for JavaScript is \, not /. So try this:

<a onClick="insertText('<img src=\"', '\">'); return false;">Image</a>

Update:

The solution above doesn't work, because the double-quotes "belong" to the HTML and not to the JavaScript, so we can't escape them in the JavaScript code.

Use this instead:

<a onClick="insertText('<img src=\'', '\'>'); return false;">Image</a> // --> <img src='...'>

or

<a onClick='insertText("<img src=\"", "\">"); return false;'>Image</a> // --> <img src="...">

Since you are using jQuery, why don't you do it the jQuery way?

insertText = function(a, b) {
    // your insertText implementation...
};

$('a').click(function() {  // use the right selector, $('a') selects all anchor tags
    insertText('<img src="', '">');
});

With this solution you can avoid the problems with the quotes.

Here's a working example: http://jsfiddle/jcDMN/

The Golden Rule for that is reversing the quotation which means I use the single quotation ' inside the double quotation " and vice versa.

Also, you should use the backslash symbole to espape a special character like ' and ".

For example, the following mands should work as they apply the rules mentioned above...

<a onClick="insertText('<em>', '</em>'); return false;">Italic</a>

or

<a onClick='insertText("<em>", "</em>"); return false;'>Italic</a>

or

<a onClick="insertText('<img src=\"', '\">'); return false;">Image</a>

or

<a onClick='insertText("<img src=\'", "\'>"); return false;'>Image</a>

I hope this helps you ...

You need to escape it.

<a onClick="insertText('<img src=\"', '\">'); return false;">Image</a>

发布评论

评论列表(0)

  1. 暂无评论