无法使用Jquery $()。attr获取循环PHP变量的attr

时间:2012-01-24 15:40:05

标签: php javascript jquery mysql

大家都在访问循环的php变量时遇到了一个小问题。我的脚本遍历并使用mysql数据库中的x和y。它还循环了我无法访问的id,它是未定义的。我正在使用鼠标输出功能来检测已经循环并获得特定ID的每个单独的div。

非常感谢帮助!

Javascript为数据库操作准备好属性:

  $(this).mouseout(function() {

   var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.

   });

循环PHP以获取attr表单:         

      $get_textsticky_result=mysql_query($get_textsticky_query);

      while($row=mysql_fetch_assoc($get_textsticky_result)){
        $x = $row['textsticky_x'];
        $y = $row['textsticky_y'];

 echo '<div class="textsticky" style="position: absolute; left:'.$x.'px; top:'.$y.'px;" textstickyid="'.$row['textsticky_id'].'">
    <div class="textstickyvalueholder"contentEditable="true">'. $row['textsticky_text'] .'  
     </div><button>Like</button></div>';

      }
      ?>

可以获得其他环状变量,例如$行[ 'textsticky_text'];和x和y的位置没有问题,有没有更好的方法来做到这一点?我有一种感觉,内联风格正在影响它,但不确定....

2 个答案:

答案 0 :(得分:4)

好吧,我只是想在这里走出困境并假设您的初始选择器不正确。 $(this)是典型代码流中的窗口。

$(this).mouseout(function() {
    var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.
});

应该是:

$('div.textsticky').mouseout(function() {
    var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.
});

另外,正如Kris在评论中提到的,使用data attribute而不是发明标签,这是html5的一部分。

<div class="textsticky" data-textstickyid="blah" />

然后可以通过jQuery的数据方法访问它。

http://jsfiddle.net/kQeaf/

只要我们提供建议,如果您使用的是jQuery 1.7+,那么您应该使用prop代替attr来访问属性(除非您决定使用{{1方法)刚刚推荐。

答案 1 :(得分:1)

mouseout事件上的选择器可能错误:(取决于上下文)

$(".textsticky").mouseout(function() {
  var stickytext_id = $(this).attr('textstickyid');
});