簡體   English   中英

在jQuery中轉義引號

[英]Escaping quotes in jquery

在以下示例中,轉義引號時出現了一些問題:

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

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

問題是,當我查看生成的代碼時,id確實更新為id="myNewId" ,但是在函數調用中,它看起來像這樣:

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

我到底在做什么錯?

只是不要將JavaScript放入HTML字符串中:

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

考慮一下,在這種特殊情況下,您可以將keyup()函數體交換為:

  runFunction(this);

因為您似乎想在對象本身上運行該函數。

您需要將HTML字符引用用於HTML屬性值。 嘗試這個:

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>');

您忘記了轉義屬性的引號。

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

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

您應使用轉義的單引號\\'#my...部分括起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM