Javascript 将带有撇号的字符串传递给javascript函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2294284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a string with apostrophe to javascript function
提问by TenHyman
I have a situation where I need to pass a string with an apostrophe in it to a javascript function. This function then takes the string and uses it to find the element by id in the DOM. As an example, I need to call:
我有一种情况,我需要将一个带有撇号的字符串传递给一个 javascript 函数。这个函数然后获取字符串并使用它在 DOM 中通过 id 查找元素。例如,我需要调用:
showElement('what's')
function showElement(element_id){
document.getElementById(element_id).style.display = "block";
}
I tried escaping the apostrophe like showElement('what\'s') but that did not seem to work. Is this possible at all?
我尝试转义像 showElement('what\'s') 这样的撇号,但这似乎不起作用。这可能吗?
采纳答案by vava
You have entirely different problem here. idattribute can't have 'symbols inside and you won't be able to search for such an id with getElementById. Escaping works though, just not in this case.
你在这里有完全不同的问题。id属性'内部不能有符号,您将无法使用getElementById. 转义虽然有效,但不是在这种情况下。
回答by Adriaan Stander
Have a look at JavaScript Escape Characters
Try using a backslash \
尝试使用反斜杠 \
Something like
就像是
showElement('what\'s')
function showElement(element_id){
document.getElementById(element_id).style.display = "block";
}
回答by jasonmw
showElement("what's")
Double quote around string with single quote inside.
字符串周围的双引号,里面有单引号。

