onmouseover показывает одинаковые данные по всем строкам таблицы - PullRequest
0 голосов
/ 03 февраля 2012

У меня возникли проблемы с получением всплывающего окна с использованием javascript для отображения данных таблицы onmouseover при наведении мыши на изображения, возвращаемые в таблицу из БД, теперь у меня проблема не в том, чтобы заставить работать onmouseover (предыдущий вопрос решил эту проблему), но получить данные, отображаемые при изменении каждого изображения, помещенного поверх.

запрос, который я использую, работает нормально и отображает правильные данные, но при onmouseover всегда отображаются только те данные, которые должны отображаться только для первой строки таблицы, во 2-й и последующих строках должны отображаться разные данные при вызове запроса ( который работает, просто не показывает onmouseover)

имейте в виду, что эта страница включена в мой index.php, который содержит все мои вызовы .js и .css

код страницы:

  <table border='0' cellpadding='0' cellspacing='0' class="center2">
  <tr>
  <td width='60'><img src="images/box_tl.png"></td>
  <td style="background: url(images/box_tm.png)" align="center"><img src="images/news.png"></td>
  <td width='25'><img src="images/box_tr.png"></td>
  </tr>
  <tr>
  <td style="background: url(images/box_ml.png)"><h2>.</h2></td>
  <td style="background: url(images/box_mm.png)">


 <?php
include 'connect.php';

$query = mysql_query("SELECT * FROM tbl_img") or die(mysql_error());;

echo "<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Mob Name</th> <th>Id</th> <th>Health</th> <th>Body</th> <th>Effects</th> <th>Spawn</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $query )) {

 $mob_id = $row['mob_id'];
 $mob = $row['mob'];
 $body = $row['body'];
$mob_name = $row['mob_name'];
 $health = $row['health'];
 $level = $row['level'];

// Print out the contents of each row into a table
echo "<tr><td>";
echo "<img src='/testarea/include/mobs/$mob' />";
echo "</td><td>";
echo $mob_name;
echo "</td><td>";
echo $level;
echo "</td><td>";
echo $health;
echo "</td><td>";





echo "
<a onmouseover='ShowPop()' href=''><img src='/testarea/include/mobs/dead/$body' /></a>
";

echo "

<div id='hidden-table' style='display:none;'>
<table border='0' cellpadding='0' cellspacing='0' class='center3'>
  <tr>
  <td width='14'><img src='images/info_tl.png'></td>
  <td style='background: url(images/info_tm.png)' align='center'></td>
  <td width='14'><img src='images/info_tr.png'></td>
  </tr>
  <tr>
  <td style='background: url(images/info_ml.png)'><h2>.</h2></td>
  <td style='background: url(images/info_mm.png)'>
";




$query2 = mysql_query("SELECT * FROM tbl_drop WHERE mob_name='$mob_name'") or die(mysql_error());

echo "<table border='0' cellpadding='1' cellspacing='1' width='250' id='2' class='tablesorter'><thead>";
 echo "<tr> <th> </th> <th>Item Name</th> <th>Qty</th></thead><tbody>";
// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $query2 )) {

$id = $row['id'];
$item_img = $row['item_img'];
$qty = $row['qty'];
$item_name = $row['item_name'];


// Print out the contents of each row into a table
echo "<tr><td width='50'>";
echo "<img src='/testarea/item/$item_img' />";
echo "</td><td width='150'>";
echo $item_name;
echo "</td><td width='50'>";
echo $qty;
echo "</td></tr>";
}

echo "</tbody></table>";


echo "
  </td>
  <td style='background: url(images/info_mr.png)'><h2>.</h2></td>
  </tr>
  <tr>
  <td width='14'><img src='images/info_bl.png'></td>
  <td style='background: url(images/info_bm.png)' align='center'><h2>.</h2></td>
  <td width='14'><img src='images/info_br.png'></td>
  </tr>
  </table>
</div>"




;
echo "</td><td>";
echo "test";
echo "</td><td>";
echo "test";
echo "</td></tr>";
}

echo "</tbody></table>";

?>




  </td>
  <td style="background: url(images/box_mr.png)"><h2>.</h2></td>
  </tr>
  <tr>
  <td width='60'><img src="images/box_bl.png"></td>
  <td style="background: url(images/box_bm.png)" align="center"><h2>.</h2></td>
  <td width='25'><img src="images/box_br.png"></td>
  </tr>
  </table>

</html>

код popup.js:

// create the popup box - remember to give it some width in your styling
document.write('<div id="pup" style="position:abolute; display:none; z-index:200;"></div>');

var minMargin = 15; // set how much minimal space there should be (in pixels)
                // between the popup and everything else (borders, mouse)
var ready = false;  // we are ready when the mouse event is set up
var default_width = 200; // will be set to width from css in document.ready
function ShowPop()
{
popup($('#hidden-table').html(), 400);
}
/* Prepare popup and define the mouseover callback */
jQuery(document).ready(function(){
$('#pup').hide();
css_width = $('#pup').width();
if (css_width != 0) default_width = css_width;
// set dynamic coords when the mouse moves
$(document).mousemove(function(e){ 
    var x,y;

    x = $(document).scrollLeft() + e.clientX;
    y = $(document).scrollTop() + e.clientY;

    x += 10; // important: if the popup is where the mouse is, the hoverOver/hoverOut events flicker

    var x_y = nudge(x,y); // avoids edge overflow

    // remember: the popup is still hidden
    $('#pup').css('top', x_y[1] + 'px');
    $('#pup').css('left', x_y[0] + 'px');
});
ready = true;
});

/*
The actual callback:
Write message, show popup w/ custom width if necessary,
make sure it disappears on mouseout
*/
function popup(msg, width)
{
if (ready) {
    // use default width if not customized here
    if (typeof width === "undefined"){
        width = default_width;
    }
    // write content and display
    $('#pup').html(msg).width(width).show();
    // make sure popup goes away on mouse out
    // the event obj needs to be gotten from the virtual 
    //   caller, since we use onmouseover='popup(msg)' 
    var t = getTarget(arguments.callee.caller.arguments[0]);
    $(t).unbind('mouseout').bind('mouseout', 
        function(e){
            $('#pup').hide().width(default_width);
        }
    );
}
}

/* Avoid edge overflow */
function nudge(x,y)
{
var win = $(window);

// When the mouse is too far on the right, put window to the left
var xtreme = $(document).scrollLeft() + win.width() - $('#pup').width() - minMargin;
if(x > xtreme) {
    x -= $('#pup').width() + 2 * minMargin;
}
x = max(x, 0);

// When the mouse is too far down, move window up
if((y + $('#pup').height()) > (win.height() +  $(document).scrollTop())) {
    y -= $('#pup').height() + minMargin;
}

return [ x, y ];
}

/* custom max */
function max(a,b){
if (a>b) return a;
else return b;
}

/*
Get the target (element) of an event.
Inspired by quirksmode
*/
function getTarget(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode;
return targ;
}

1 Ответ

1 голос
/ 03 февраля 2012

Все скрытые таблицы имеют одинаковые идентификаторы, но идентификаторы должны быть уникальными.

предоставляет ссылку в качестве аргумента для ShowPop ()

<a onmouseover='ShowPop(this)' ....>

, тогда вы сможетечтобы получить доступ к намеченной цели внутри ShowPop ():

function ShowPop(o)
{
popup($(o).next('div').html(), 400);
}

Редактировать:

По поводу комментария:
В настоящее время я думаю, что всплывающее окно будетне исчезать onmouseout в любом браузере (кроме IE), потому что вы не предоставили аргумент ShowPop (), что в других браузерах необходимо для возврата чего-либо из getTarget, потому что они не знали window.event.

Измените эту строку:

var t = getTarget(arguments.callee.caller.arguments[0]);

на

var t = arguments.callee.caller.arguments[0];

... потому что, когда вы берете мое предложение, ссылка уже предоставляется в качестве аргумента для ShowPup (), нет необходимости вызывать getTarget ().

...