当用户将鼠标悬停在表格上以触发预览事件时,它不会以任何方式做出反应。我认为问题在于表行是通过PHP生成的。
HTML,PHP
<table>
<thead>
<tr>
<th width="200">User</th>
<th width="900">Description</th>
</tr>
</thead>
<tbody>
<?php
require_once './Classes/MainController.php';
$mc = MainController::getInstance();
$threads = $mc->getAllThreads();
foreach ($threads as $thread) {
?>
<tr id='thread_video_preview'>
<td><?php print $thread->original_poster; ?></td>
<td><?php print $thread->description; ?></td>
<td id='see_thread_video_url' class="hide"><?php print $thread->url; ?></td>
</tr>
<?php } ?>
<script type="text/javascript" src="./Javascript/MainFunctions.js"> HoverPreview();
</script>
</tbody>
</table>
Jquery function HoverPreview() {
$('tr#thread_video_preview').hover(function() {
var url = $(this).$('#see_thread_video_url').html();
$('#dynamicPreview').html('<iframe width="320" height="240" src="//www.youtube.com/embed/' + url + '?autoplay=1" frameborder="0""></iframe>')
});
}
这里有几个问题。首先,id
属性必须是唯一的。如果要对元素进行分组,请使用类。其次,script
标签的位置可能会导致问题。你应该把它放在head
中,或者就在</body>
之前。最后,当您设置script
标记的src
属性时,您不能在其中放置任何代码。为此您需要一个单独的脚本标记。记住所有这些,试试这个:
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="./Javascript/MainFunctions.js"></script>
<script type="text/javacript">
$(function() {
$('tr.thread_video_preview').hover(function() {
var url = $(this).find('.see_thread_video_url').html();
$('#dynamicPreview').html('<iframe width="320" height="240" src="//www.youtube.com/embed/' + url + '?autoplay=1" frameborder="0""></iframe>')
});
});
</script>
</head>
正文:
<?php
require_once './Classes/MainController.php';
$mc = MainController::getInstance();
$threads = $mc->getAllThreads();
foreach ($threads as $thread) { ?>
<tr class='thread_video_preview'>
<td><?php print $thread->original_poster; ?></td>
<td><?php print $thread->description; ?></td>
<td class='see_thread_video_url' class="hide"><?php print $thread->url; ?></td>
</tr>
<?php }
?>
修改
<tr id='thread_video_preview'>
To:
<tr class='thread_video_preview'>
在jquery事件中使用
$(".thread_video_preview").
我认为在td
而不是tr
中使用属性或事件侦听器是很好的做法