开发者

How to fix this java script error handling single quote in the line

Hi I had a similar requirement as below and was curious to know to fix the issue.

Below is the code

<script type="text/javascript">
function Msg1(){
  var sd= document.getElementById('myText').innerHTML = 'Th开发者_StackOverflowank's!';
  alert('-sd-'+sd);
}
function Msg2(){
  document.getElementById('myText').innerHTML = 'Try messages 1 again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1" />
<input type="button"  onclick="Msg2()" value="Show Message 2" />
<p id="myText"></p> 

The innerHTML tag is throwing script error like

Webpage error details


Message: Expected ';'
Line: 29
Char: 64
Code: 0
URI: file:///C:/Documents%20and%20Settings/j1007962/Desktop/spl.html

I was looking for the fix around innerHTML or better replace with something which would fix this . Thanks


You should escape your quotes.

Modify

var sd= document.getElementById('myText').innerHTML = 'Thank's!';

To

var sd= document.getElementById('myText').innerHTML = 'Thank\'s!';

Or use double quotes

var sd= document.getElementById('myText').innerHTML = "Thank's!";


Try to escape the single quote

var sd= document.getElementById('myText').innerHTML = 'Thank\'s!';

Edit

Let say we have some text coming from Server side or from a HTML tag. In that case we have a valid variable. So there is no need to change that variable.

<div id="div1">
    Thank's!
</div>

<script language="javascript" type="text/javascript">

function changeDivHTML()
{
    var innerText = document.getElementById('div1').innerHTML;

    alert( innerText );
}

OR if the text is coming from server via Ajax

$.ajax({
    url: "test.html",
    success: function(data){
        alert( data.someStringValue );
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜