Javascript <tr> onClick 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5319638/
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
<tr> onClick not working
提问by AKor
I want to turn my table rows into links using JS. I have it looking like this:
我想使用 JS 将我的表格行转换为链接。我有它看起来像这样:
<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:
至于引号,我忘了提到我正在用 PHP 回应这一点。这是我更新的代码:
echo "<tr onClick='window.location.href='url?id=" . $var . "';'></tr>";
Should I be doing some sort of escaping like /"
in this case?
/"
在这种情况下,我应该做某种逃避吗?
回答by ThiefMaster
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.
首先,在事件处理程序中没有javascript:
- 它们包含 JavaScript 代码,而不是 URL。它只是有效,因为javascript:
在这种情况下是一个标签,因此不是语法错误。除此之外,任何具有正确语法突出显示的编辑器都会向您表明您正在破坏引用,因为您对 HTML 属性和属性内部使用单引号。
Here's the fixed code:
这是固定代码:
<tr onclick="window.location.href = 'url';">
Besides that, inline event handlers are dirty. Better attach them nicely using jQuery:
除此之外,内联事件处理程序很脏。更好地使用 jQuery 很好地附加它们:
$('tr').click(function() {
location.href = 'url';
});
回答by Jeremy Conley
As you know, HTML attributes have to be surrounded by quotes, so if you need quotes withinthe attribute you need a different pairing. Try this:
如您所知,HTML 属性必须用引号括起来,因此如果您需要在属性中使用引号,则需要不同的配对。尝试这个:
<tr onClick="window.location.href='url';">
And if you are within a loop and echo'ing stuff out try PHP's HEREDOC syntax.
如果您在循环中并回显内容,请尝试 PHP 的 HEREDOC 语法。
$out = '';
foreach ( $x as $y )
{
$out .= <<<HTML
<tr onClick="window.location.href='url';">
HTML;
}
echo $out;
Edit: added HEREDOC
编辑:添加了HEREDOC