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

javascript - Escaping quotes in jquery - Stack Overflow

programmeradmin3浏览0评论

I'm having a bit of a problem escaping quotes in the following example:

var newId = "New Id number for this line";

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');

The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:

onkeyup="runFunction(" #row2="" );=""

What exactly am I doing wrong?

I'm having a bit of a problem escaping quotes in the following example:

var newId = "New Id number for this line";

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');

The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:

onkeyup="runFunction(" #row2="" );=""

What exactly am I doing wrong?

Share Improve this question asked Jun 4, 2010 at 15:01 rshiversrshivers 1471 gold badge1 silver badge11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

Just don't put JavaScript into the HTML string:

$(id).html(
  '<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
  runFunction("#my" + newId);
});

Thinking about it, in this special case you can exchange the keyup() function body for:

  runFunction(this);

because you seem to want to run the function on the object itself.

You need to use HTML character references for HTML attribute values. Try this:

function htmlEncode(str) {
    var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
    return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');

You forgot to escape the attribute's quotes.

var newId = "New Id number for this line";

$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');

You should use escaped single quotes \' to surround the #my... part.

发布评论

评论列表(0)

  1. 暂无评论