[英]Escaping Apostrophes in Javascript Generated From PHP
我正在嘗試使用一個帶有初始值的文本字段,如果單擊它,文本將消失,並且如果在輸入任何內容之前單擊退出,則初始值將返回,就像Yahoo答案和許多其他站點上的搜索框一樣。
echo "<input type=\"text\"
onblur=\"if (this.value == '') {this.value = '$cleaned';}\"
onfocus=\"if (this.value == '$cleaned') {this.value = '';}\"
value=\"$cleaned\" />\n";
我有一個PHP變量$cleaned
作為我的初始值。 該代碼有效,除了其中cleaned變量中帶有撇號的情況(例如$cleaned = "FRIEND'S"
。 然后代碼會讀this.value = 'FRIEND'S'
和在撇號FRIEND'S
早結束的字符串。
我嘗試使用html實體,轉義撇號和使用轉義引號,但無法使這種情況起作用。 到目前為止,我唯一的解決方案是用看起來像撇號的字符替換撇號。
有誰知道如何處理這種情況?
使用json_encode
編碼要在JavaScript中使用的數據,並使用htmlspecialchars
編碼要在HTML屬性值中使用的字符串:
echo '<input type="text"
onblur="'.htmlspecialchars("if (this.value == '') {this.value = ".json_encode($cleaned).";}").'"
onfocus="'.htmlspecialchars("if (this.value == ".json_encode($cleaned).") {this.value = '';}").'"
value="'.htmlspecialchars($cleaned).' />'."\n";
但是使用defaultValue
當然更容易:
echo '<input type="text"
onblur="'.htmlspecialchars("if (this.value == '') {this.value = defaultValue;}").'"
onfocus="'.htmlspecialchars("if (this.value == defaultValue) {this.value = '';}").'"
value="'.htmlspecialchars($cleaned).'" />'."\n";
首先生成純JavaScript代碼。 您可以使用json_encode創建有效的JavaScript值,如下所示:
$js = 'if (this.value == '.json_encode($cleaned).') {this.value = "";}';
然后生成HTML。 您可以使用htmlspecialchars編碼所有HTML屬性,包括那些包含內聯JavaScript代碼的屬性,如下所示:
echo '<input type="text" onblur="'.htmlspecialchars($js).'" />';
這個怎么樣
echo '<input type="text"
onblur="if (this.value == "") {this.value = "' . $cleaned . '";}"
onfocus="if (this.value == "' . $cleaned . '") {this.value = "";}"
value="' . $cleaned . '" />\n';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.