2011-03-09 87 views
0

我動態添加一個文本框的值,如:分配特殊字符的文本框

$('.myClass').html("<input type='text' class='txtVector' value='" + textValue + "'>"); 

當我加入來自一個名爲「textValue」變量中的文本框的值。但問題是,如果變量「textValue」包含帶單引號(')或雙引號(「)的值,如abcd'xyz或abcd」xyz,則文本框的值看起來像這個值=「abcd'xyz」或值=「abcd」xyz「。在這種情況下,值會截斷,只要它獲得下一個報價。我的意思是textbox的值將只有abcd不abcd'xyz。誰能建議如何解決這個問題?

+0

你想用空字符串替換單引號字符? – Sarfraz 2011-03-09 14:24:44

回答

4

您可以使用val()

$('.myClass').html("<input type='text' class='txtVector'>").children().val(textValue); 

或者

$('.myClass').append(
    $("<input type='text' class='txtVector'>").val(textValue) 
); 

或者

$("<input type='text' class='txtVector'>").val(textValue).appendTo(".myClass"); 

請參閱val(string) docs。這具有正確處理其他特殊字符的優點(例如,&)。

+2

你確定.html()會發送回輸入元素嗎?我雖然會發回$('。myClass')。 – 2011-03-09 14:27:06

+0

@Louskan:哈哈!謝謝。固定。 – 2011-03-09 14:31:07

2

也許這樣做兩次應該做的工作?

$('.myClass').html("<input type='text' class='txtVector' value='' id='whatever'>"); 
$('#whatever').val(textValue); 
3

嘗試這樣的:

$('.myClass').html(
    $('<input/>') 
     .attr('type', 'text') 
     .addClass('txtVector') 
     .val(textValue) 
); 

或者如果你喜歡:

$('.myClass').html(
    $('<input/>', { 
     type: 'text', 
     class: 'txtVector', 
     value: textValue 
    }) 
); 
1
var $html=$("<input type='text' class='txtVector'>").val(textValue); 
$('.myClass').empty().append($html);