开发者

Passing a string with apostrophe to javascript function

开发者 https://www.devze.com 2022-12-20 20:20 出处:网络
I have a situation where I need to pass a string with an apostrophe in it to a javascript function.Thi开发者_运维问答s function then takes the string and uses it to find the element by id in the DOM.A

I have a situation where I need to pass a string with an apostrophe in it to a javascript function. Thi开发者_运维问答s function then takes the string and uses it to find the element by id in the DOM. As an example, I need to call:

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?


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"; 
} 


You have entirely different problem here. id attribute 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.


showElement("what's")

Double quote around string with single quote inside.

0

精彩评论

暂无评论...
验证码 换一张
取 消