<tr> onClick not working

こ雲淡風輕ζ 提交于 2019-12-06 19:06:01

问题


I want to turn my table rows into links using JS. I have it looking like this:

<tr onClick='javascript:window.location.href='url';'>

However, when I try to click, it doesn't go the page as I want. In fact, clicking seems to have no action.

Any help?

Edit:

As for the quotes, I forgot to mention that I'm echoing this with PHP. Here's my updated code:

echo "<tr onClick='window.location.href='url?id=" . $var . "';'></tr>";

Should I be doing some sort of escaping like /" in this case?


回答1:


First of all, no javascript: in event handlers - they contain JavaScript code, not an URL. It just works because javascript: is a label in this case and thus not a syntax error. Besides that, any editor with proper syntax highlighting would have shown you that you are breaking the quoting as you are using single quotes for the HTML attribute and inside the attribute.

Here's the fixed code:

<tr onclick="window.location.href = 'url';">

Besides that, inline event handlers are dirty. Better attach them nicely using jQuery:

$('tr').click(function() {
    location.href = 'url';
});



回答2:


As you know, HTML attributes have to be surrounded by quotes, so if you need quotes within the attribute you need a different pairing. Try this:

<tr onClick="window.location.href='url';">

And if you are within a loop and echo'ing stuff out try PHP's HEREDOC syntax.

$out = '';
foreach ( $x as $y )
{
$out .= <<<HTML
<tr onClick="window.location.href='url';">
HTML;
}
echo $out;

Edit: added HEREDOC



来源:https://stackoverflow.com/questions/5319638/tr-onclick-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!