开发者

How to pass long value to javascript function

I have javascript function:

function someAction(thisTd,text){
  alert(text);
  thisTd.innerHTML=text;
  ...
}

And html-file:

<td onclick="someAction(this,<?echo 'Long-long text with <b>html-formatting</b>'?>)"/>

When I use such code function someAction doesn't call (because alert doesn't show) and in the error console in Opera no error is displayed. How to fix this problem?

P.S. I do not use frameworks(JQuery etc.).

UPDATE #1

When I use such code:

<?$encoded=str_replace("\n","",str_replace("\r\n","",$text));echo $encoded?>
开发者_Go百科

It works nice. But I'm not sure, that it work correct in Linux.(I use Windows)


Make sure that you HTML encode it and put single quotes around the parameter:

<td onclick="someAction(this, '<?echo htmlspecialchars('Long-long text with <b>html-formatting</b>', ENT_QUOTES) ?>')"/>


You should remoce echo tag and the ?

 <div onclick="someAction(this,'Long-long text with <b>html-formatting</b>')">myDiv</div>

and your function is :

function someAction(thisTd,text){
    thisTd.nodeValue=innerHTML
    ...
}


You must wrap the string in single or html encoded double quotes in the first place:

<td onclick="someAction(this, '<?php echo 'yada yada'; ?>');"/>
<!-- OR -->
<td onclick="someAction(this, &quot;<?php echo 'yada yada'; ?>&quot;);"/>

Secondly, the "echo"ed output can contain single or double quotes that can break the javascript string or the html attribute. Assuming that you're using single quotes to wrap the echoed string:

<td onclick="someAction(this, '<?php echo htmlspecialchars( str_replace( "'", "\\'", $that_long_text ) ); ?>');"/>


Just put the quotes around the text, you're producing:

Logically, this gives an error.

Use simple quotes or escape double quotes (\")

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜