【问题标题】:How to apply onclick event to html tag when it displays in a loophtml标签循环显示时如何将onclick事件应用于html标签
【发布时间】:2016-11-02 08:05:24
【问题描述】:

我创建了一个从 MySQL 数据库中检索数据的 PHP 页面。我在数据库中插入了四条记录。数据在 index.php 页面上显示良好,但我想显示记录,如附在此处的图像中所示。我希望所有记录都关闭,当点击名称时它会打开。其他保持关闭,当其他打开时关闭。现在,当我单击任何名称时在浏览器中运行时,仅显示第一条记录。 (或使用 php、MySQL 等执行此操作的任何其他方式。)有什么帮助吗?

index.php:

<?php

ob_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'test');

$connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());

$select=mysql_query("SELECT * FROM sample order by id desc");
$i=1;
while($userrow=mysql_fetch_array($select))

{
$id=$userrow['id'];
$username=$userrow['username'];
$usercity=$userrow['usercity'];
$useraddress=$userrow['useraddress'];
$usermail=$userrow['emailid'];
$usermobile=$userrow['mobileno'];
$created=$userrow['created']
?>
<div class="display" style="width:500px">
<!-------------------- User Name : --------------------------------->
  <p id="User-Name" style="color:#999" onclick="showDiv();"> Name- <span style="color: #999"><?php echo $username; ?></span>
  <span class="delete" title="Delete"> X </span></a>
  </p>
  <br />
<!--------------------- User City : ----------------------------------->
  <p style="margin-left: 300px; margin-top: -45px; color:#999">City- <span style="color:#999"><?php echo $usercity; ?></span></p>
  <br />

  <div id="Entries" >
<!---------------------- User address : -------------------------------->
  <p style="color:#999">Address-  <span style="color:#999"><?php echo $useraddress; ?></span>

  </p>
  <br />
<!------------------ User Email Id : -------------------------------->  
  <p style="color:#999">Email-  <span style="color:#999"><?php echo $usermail; ?></span>
    <a href="edit.php?id=<?php echo $id; ?>"><span class="edit" title="Edit"> E </span></a>
  </p>
<!--------------------- User Mobile : --------------------------------->
  <br />
  <p style="color:#999">Mobile-  <span style="color:#999"><?php echo $usermobile; ?></span>
  </p>
 <!-------------------- User Created : -------------------------------> 
  <br />
  <p style="color:#999">  <span style="color:#999"><?php echo $created; ?></span>
  </p>
  <br />
  </div>
</div>

<?php } ?>

<script>
function showDiv() 
{
  document.getElementById('Entries').style.display = "block";
}
</script>

<style>
#Entries
{
  display:none;
}
</style>

【问题讨论】:

  • 因为当我运行 index.php 时出现 while 循环,“Display” div 会显示页面上的所有记录,但“Display” div 是复制的,所以 onclick 事件也会复制。当我单击任何名称并每次显示第一条记录时,它们的 onclick 事件就会触发一次。如何解决这个问题!
  • 而不是id for Entries,尝试将其更改为class 并再次测试。因为id 可以为第一个工作。并在你的函数中更改getElementByClassName()
  • 是的,我尝试过,但是“条目”div 中的数据是隐藏的,没有点击名称的活动。我认为 onclick="showDiv(); 是独一无二的。我认为如果为记录 1 分配动态 onclick 事件,如 showDiv1() 等等,那么问题就解决了,但是如何解决?
  • 手风琴最适合这种情况jqueryui.com/accordion
  • 我尝试“手风琴”对静态数据有好处。但是,因为“Entries” div 在循环中,它会重复,所以
    也是重复和冲突的,只有第一条记录是显示的。

标签: javascript php html css


【解决方案1】:

在一个文档中id是唯一的,这意味着只能提供一个id,所以将你的&lt;div id="Entries" &gt;更改为&lt;div class="Entries" &gt;(同时循环打印多次相同的div标签)。

现在将您的 onclick 事件从 &lt;p&gt; 更改为 &lt;div&gt;,如下所示: &lt;p style="color:#999" onclick="showDiv();"&gt;改成&lt;div class="display" onclick="showDiv(this);" style="width:500px;border:1px solid #eee;margin-bottom:2px;"&gt;(那么只有你可以选择div.display里面的'div.Entries',而不是&lt;p&gt;里面的'div.Entries')

现在将代码底部的 CSS 样式标签从 #Entries 更改为 .Entries(因为我们在 div 中进行了更改)

只需将以下代码添加到您的页面

<script>
function showDiv(obj) 
{
    $('.Entries').css('display','none');
 var div = $(obj).find('.Entries').css('display','block');
}
</script>

完整的代码如下:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
    </head>
<body>
      <?php

      $database = array(
      'one' => array('name' => 'john' , 'city' => 'noida' , 'addr' => 'xyz','mail' => 'john@xyz.com'),
      'two' => array('name' => 'jimi' , 'city' => 'india' , 'addr' => 'abc','mail' => 'jimi@abc.com'),
      'three' => array('name' => 'foo' , 'city' => 'china' , 'addr' => 'pqr','mail' => 'foo@pqr.com'),
      'four' => array('name' => 'apple' , 'city' => 'america' , 'addr' => 'lmno','mail' => 'apple@lmno.com'),
      );

           foreach ($database as $row) {

            $username = $row['name'];
            $usercity = $row['city'];
            $useraddress = $row['addr'];
            $usermail = $row['mail'];

        echo    '<div class="display" onclick="showDiv(this);" style="width:500px;border:1px solid #eee;margin-bottom:2px;">
            <!-------------------- User Name : --------------------------------->
              <p style="color:#999"> Name- <span style="color: #999">'.$username.' ?></span>
              <span class="delete" title="Delete"> X </span></a>
              </p>
              <br />
            <!--------------------- User City : ----------------------------------->
              <p style="margin-left: 300px; margin-top: -45px; color:#999">City- <span style="color:#999">'.$usercity.'</span></p>
              <br />

              <div class="Entries" >
            <!---------------------- User address : -------------------------------->
              <p style="color:#999">Address-  <span style="color:#999">'.$useraddress.'</span>

              </p>
              <br />
            <!------------------ User Email Id : -------------------------------->  
              <p style="color:#999">Email-  <span style="color:#999">'.$usermail.'</span>
                <a href="edit.php?id=<?php echo $id; ?>"><span class="edit" title="Edit"> E </span></a>
              </p>
              <br />
              </div>
            </div>';
    }

      ?>

</body>
<script>
function showDiv(obj) 
{
    $('.Entries').css('display','none');
 var div = $(obj).find('.Entries').css('display','block');
}
</script>

<style>
.Entries
{
  display:none;
}
</style>
</html>

【讨论】:

  • 谢谢先生。这真的很有帮助,我只是修改循环 foreach 在我的情况下不起作用,所以 while 循环工作正常,我期待的问题得到了解决。
【解决方案2】:

id 属性值在 HTML 页面上的每个元素都必须是唯一的。因此,保存数据库信息的&lt;div&gt; 元素集合应分配为class,而不是id

jsfiddle Example

文档:

.animate()

.addClass()

.hasClass()

.click()

    var $entryCollectionArray = $('div.entries')
     $entryCollectionArray.click(function(i) {
      var $brothers = $(this).siblings();
      var $activeEntry = $(this);
      $brothers.addClass('notActive').removeClass('active');
      $activeEntry.addClass('active');
      if ($activeEntry.addClass('active')) {
        $activeEntry.animate({
          height: '120px'
        }, 550);

        $brothers.animate({
          height: '18px'
        }, 550);
      }
    });
div {
  width: 250px;
  height: auto;
  background-color: #ACE;
  clear: both;
  margin-bottom: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class='entries'>
  mySQL 1
</div>
<div class='entries'>
  mySQL 2
</div>
<div class='entries'>
  mySQL 3
</div>
<div class='entries'>
  mySQL 4
</div>

【讨论】:

    【解决方案3】:

    你可以使用 jQuery:

    $('div.display').click(function() {
        // hide all the divs
        $('div.display').css('display', 'none');
    
        // display only the current one using $(this) reference
        $(this).css('display', 'block');
    });
    

    编辑:

    class="username" 添加到用户名&lt;p&gt; 元素

    class="entries" 添加到条目&lt;div 元素中

    把代码改成

    $('.username').click(function() { 
        // hide all the divs
        $('div.entries').css('display', 'none');
    
        // display only the current one using $(this).parent() reference
        // because you are clicking the username element
        $(this).parent().css('display', 'block');
    });
    

    【讨论】:

    • 我尝试上面的 j 查询代码,但没有任何反应!我该怎么办?
    • 你是否把它放在&lt;script&gt; 标签中,并在你的.html 文件中包含jQuery?将此复制到您的 &lt;head&gt; 中:&lt;script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"&gt;&lt;/script&gt;
    • $('#User-Name').click(function() { $('#Entries.display').css('display', 'none'); $(this). css('显示', '块'); });我试试这个,但没有任何反应......!
    • 编辑了我原来的答案。
    【解决方案4】:

    只需将user_id 传递给该函数,以便它成为各个 div 的唯一函数。还要给那个 div 唯一的 id,比如 id="user_info_panel_&lt;?php echo $user_id; ?&gt;"

    例如:

    $user_id: 2;
    onclick="return clickme($user_id);"
    

    【讨论】:

    • 好吧,我可以试试……但是,我如何给 div 一个“唯一”id,因为它只是你在代码中看到的一个。当我运行 index.php 时,
      将返回浏览器中的记录数,因此,
      中的整个标签和属性都会为每条记录克隆。那么如何做到这一点呢?
    猜你喜欢
    • 2011-05-17
    • 2023-01-24
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2020-03-04
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多