【问题标题】:Get the id value of two different divs with the same class获取同一个类的两个不同div的id值
【发布时间】:2013-02-11 02:59:14
【问题描述】:

好的,我正在创建一个私人消息系统,我已将 php 设置为回显具有相同类的 div,但将 id = 设置为行 ID,请检查下面的代码。

function Load()
{

$Connect = new mysqli("localhost", "root", "", "Data");
session_start();
$User = $_SESSION['Username'];
$Stats = 'SELECT * FROM Messages WHERE User="'.$User.'"';

if($Result = $Connect->query($Stats))
{
    while($Row = $Result->fetch_assoc())
    {
        $From = $Row['FUser'];
        $Date = $Row['Date'];
        $Title = $Row['Title'];
        $ID = $Row['ID'];

        echo '<div id="'.$ID.'" class="String"><label class="TText" style="cursor:pointer;">From: ' . $From . ' - ' . $Date . ' - ' . $Title .'</label></div>';
    }
}

}

我的 JQuery:

$('.String').click(function()
{
    var Msg = $('#MMsg');
    var Back = $('#Back');
    var Str = $('.String');
    Str.fadeOut('fast', function()
    {
        Msg.fadeIn('fast');
        Back.fadeIn('fast');
        var ID = $('.String').attr('id');

        $.ajax
        ({
            url:'MLoad.php',
            type:'POST',
            data:{ID:ID},
            dataType:'json',
            success:function(MText)
            {
                $('#MMBox').html(MText.T);
            }
        });
    });
});

当我提醒 var ID 时,两个 div 的结果相同,但在 html 中,每个 div 的 ID 不同。即警报框每次都给我第一个 ID。

【问题讨论】:

    标签: php jquery ajax html


    【解决方案1】:

    使用 $(this) 获取正在应用淡出的元素的 ID。否则你只会得到第一个匹配的 div 的 ID。

    var ID = $(this).attr('id');

    【讨论】:

      【解决方案2】:

      当您在点击函数中时,this 指的是被点击的项目。所以你可以使用$(this).attr('id')来检索被点击的.String的ID。

      $('.String').click(function()
      {
          var id = $(this).attr('id');
          var Msg = $('#MMsg');
          var Back = $('#Back');
          var Str = $('.String');
          Str.fadeOut('fast', function()
          {
              Msg.fadeIn('fast');
              Back.fadeIn('fast');
      
              $.ajax
              ({
                  url:'MLoad.php',
                  type:'POST',
                  data:{ID:id},
                  dataType:'json',
                  success:function(MText)
                  {
                      $('#MMBox').html(MText.T);
                  }
              });
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 2013-01-24
        • 2020-08-07
        • 2023-03-20
        • 2021-10-29
        相关资源
        最近更新 更多