开发者

How do I Include Nested Quotes HTML?

开发者 https://www.devze.com 2023-04-03 04:56 出处:网络
How do I property incl开发者_如何学运维ude quotes in a string? I want to do something like this:

How do I property incl开发者_如何学运维ude quotes in a string? I want to do something like this:

var stringvariable;
$('#somediv').append('<a href id="someid" + onclick="doSomething("'+stringvariable+'")> MyLink"+</a>');

The problem has to do with the following part: onclick="doSomething("'+stringvariable+'")

How do I allow nested double quote since I need to be able to do: onclick="doSomething("stringvalue")"


You can escape the quotes within the string using back slashes \:

var stringvariable;
$('#somediv').append('<a href id="someid" + onclick="doSomething(\''+stringvariable+'\')> MyLink"+</a>');


You could use escapes to accomplish this, but for legibility, I'd suggest doing:

$('#somediv')
    .append('<a href id="someid">MyLink</a>')
    .click(function() {
       doSomething(stringvariable);
    });


Use single qoutes instead.

onclick="doSomething('stringvalue')"


If you're using jQuery, use it throughout. The following would be better and easier to maintain:

var $a = jQuery("<a></a>")
    .attr("id", "someid")
    .attr("href", "http://example.com")
    .text("My Link")
    .click(function() {
   doSomething("stringvalue");
});
jQuery("#somediv").append($a);


Javascript uses both ' and " as string delimiters so use this to your advantage.

onclick="doSomething('value');" 


How about this alternate method? Will accomplish what you're trying to do and should hopefully prove a bit more readable:

var stringVariable = "foo";

$('<a/>', 
    { id: "someid", 
      text: "MyLink"
    } 
 ).click( function() { doSomething(stringVariable) } )
  .appendTo("#somediv");


you can use

onclick="doSomething(\"stringvalue\")";
0

精彩评论

暂无评论...
验证码 换一张
取 消