问题
Scenario : When <div>
text has double quote. JQuery method to append dynamic input and to alert the value of input is not working. I know this issue trigger when escaping quotes. Can someone review the code?
var divText = $("div").text();
$('form:not(:has([name="' + divText + '"]))').append($('<input>', {
type: 'text',
value: divText,
name: divText
}));
alert($('[name="' + divText + '"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>"</div>
<form>
</form>
I've created some demo here
回答1:
Playing off the reg exp from the jQuery docs
var divText = $("div").text();
var name = divText.replace(/("|:|\.|\[|\]|,)/g, "\\$1");
$('form:not(:has([name="' + name + '"]))').append($('<input>', {
type: 'text',
value: divText,
name: divText
}));
alert($('[name="' + divText + '"]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>"</div>
<form>
</form>
回答2:
If you must use double quotes, you can remove them like so:
var divText = $("div").text().replace(/"/g, '');
Fiddle
来源:https://stackoverflow.com/questions/31576216/dynamic-input-name-with-double-quotes-issue