2015-04-15 16 views
1

我現在正在用下面的問題解決問題,並且我已經沒有想法了。從來就一個選擇框與具有HTML字符在他們的價值領域不同選項:當值爲HTML時,通過它的值選擇一個元素字符

<select>  
<option value="Zinksulfat" selected="selected">Zinksulfat</option> 
<option value="Zypressen&ouml;l" selected="selected">Zypressenöl</option> 
<option value="Wirkstoff&quot;Mit'Anf&uuml;hrungszeichen" selected="selected">Wirkstoff"Mit'Anführungszeichen</option> 
</select> 

爲了使用這個簡單的功能的jQuery I'm變量HTML編碼:

function htmlEntities(str) { 
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace('ü', '&uuml;').replace('ö', '&ouml;'); 
} 

現在我試圖通過它的值(「選擇」是選擇框)獲得選項對象:

// Set the element value 
var elementValue = 'Wirkstoff"Mit'Anführungszeichen'; // Invalid I know - only for description purpose 
    elementValue = htmlEntities(elementValue); 

return select.find('option[value="'+elementValue+'"]')[0]; 

因此,對於沒有HTML字符的元素,它就像一個魅力(例如。 「Zinksulfat」)。但對於具有HTML字符的元素,它不起作用。雖然「elementValue」中的值和值字段完全相同,但我收到「undefined」。

有沒有人知道要做什麼神奇的事情,以便我可以在選擇器中使用HTML字符?

由於提前, 邁克爾

+1

只是逃避correctly.refer http://jsfiddle.net/769gp0nn/ –

+1

我的回答是矯枉過正(刪除)字符串..只需將@VJ Sai建議的正確格式化爲字符串:) –

+0

@VJ Sai:將您的評論發佈爲答案(在別人之前) –

回答

0

你不需要你的功能在所有。這僅僅是獲得正確字符串的情況(在單引號字符串中轉義任何單引號)。該HTML編碼翻譯由jQuery的爲你做:

var elementValue = 'Wirkstoff"Mit\'Anführungszeichen'; 
$("select").find('option[value="'+elementValue+'"]').css("color", "red"); 

的jsfiddle:http://jsfiddle.net/TrueBlueAussie/prnxbdp8/

選擇下拉另一種選擇地看到,這場比賽是現在紅。

-1

它很容易修復。您需要轉義elementValue。

只是做:

elementValue = htmlEntities(elementValue); 

function htmlEntities(str) { 
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace('ü', '&uuml;').replace('ö', '&ouml;'); 
} 

,它應該工作。 https://jsfiddle.net/8pf9vooc/

+0

發表答案是一回事,但是你的例子並沒有這樣做。你甚至不會在你的JSFiddle中包含'elementValue'。 –

+0

這是一個誤解......不是逃避功能是問題。包含HTML字符的選擇器是...... – Michael

0

我剛剛在一些更多的測試後找到了解決方案 - 也許它可以幫助別人。

不能與HTML字符的工作:

return select.find('option[value="'+elementValue+'"]')[0]; 

作品:

// Find and return the option element from select box 
var foundOption = select.find('option').filter(function() { 
    return (htmlEntities(this.value) == elementValue); 
}).show(); 

return foundOption[0]; 
+0

這與我原來的相似(查看我的編輯),但不需要'htmlEntities',因爲該翻譯是由jQuery爲您完成的。 –

0

而不是使用它的工作原理與.filter()方法select.find()方法問題在於轉義字符串。請參閱小提琴獲取解決方案。

http://jsfiddle.net/769gp0nn/

function htmlEntities(str) { 
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace('ü', '&uuml;').replace('ö', '&ouml;'); 
} 

var elementValue = 'Wirkstoff"Mit\'Anführungszeichen'; 

console.log($("select").find('option[value="'+elementValue+'"]')[0]); 
+0

注意:'\「'不是*要求在用''分隔的字符串中。」 –

+0

修改了謝謝。@TrueBlueAussie –

相關問題