2016-12-01 58 views
-2

我正在生成一个菜单,其中包含从foreach生成的select查询中的列表项。从使用foreach生成的项目获取变量

我正在打印每行的'名称'。但是,我还想在变量内存储一些其他数据,所以当我点击一个<li>时,我会得到这些特定的变量。

我想用Javascript做到这一点,所以我不刷新页面。

下面的代码我到目前为止:

$query = "SELECT * FROM credenciais_sensores where ambiente = '1'"; 
$results = mysqli_query($conn, $query); 

<ul class="treeview-menu"> 
    <?php foreach ($results as $result) { 
    $local = $result['local']; 
    $local = substr($local,0,7); 
    echo "<li><a class='post' href='#'>".$local."</a></li>"; 
    }?> 
</ul> 

我怎样才能做到这一点?

回答

0

下面的代码

<ul class="treeview-menu"> 
    <?php 
    foreach ($results as $result){ 
     $local = $result['local']; 
     $local = substr($local,0,7); ?> 
     <li><a class="post" href="#<?=$local;?>"><?=$local;?></a></li> 
     <div id="<?=$local;?>">some details...</div> 
    <?php } ?> 
</ul> 

<?php foreach ($results as $result){ 
      $local = $result['local']; 
      $local = substr($local,0,7); ?> 
      <div id="<?=$local;?>">some details...</div> 
    <?php } ?> 
0

如果我得到你的权利,你想从DB /后端到每个菜单的项目元素您在foreach循环创建数据绑定,然后在项目元素点击事件,获取该项目的具体数据。如果你有这样的意思,那么有多条路可走。现在,我将向您展示一个示例:创建项目元素时,您可以创建数据属性以将数据保存为字符串化对象,并在点击事件中解析它,在PHP部分中,我创建了一个模拟结果数组以内部数组为例,“other_data”键包含要绑定到item元素的数据,然后在foreach循环中添加“data-other”属性以包含其他数据作为strigify对象。我已经为示例提交了“substr”函数,稍后您可以不提交。与“显示数据的” ID的新的div只是打印上点击事件的每个项目的数据:

<ul class="treeview-menu"> 
<?php 
$results = array(
    array(
     'local' => 'some local 1', 
     'other_data' => array(
      'other_data1' => 'some other data 1 from local 1', 
      'other_data2' => 'some other data 2 from local 1' 
     ) 
    ), 
    array(
     'local' => 'some local 2', 
     'other_data' => array(
      'other_data1' => 'some other data 1 from local 2', 
      'other_data2' => 'some other data 2 from local 2' 
     ) 
    ) 
); 
$item = ''; 
foreach ($results as $result){ 
    $local = $result['local']; 
    //$local = substr($local,0,7); 
    $other_data = json_encode($result['other_data']); 
    $item .= "<li><a class='post' href='#' data-other='$other_data'>$local</a></li>"; 
} 
echo $item; 
?> 
</ul> 
<div id="display-data"></div> 
在JS部分

,我们对所有菜单的项目元素的运行for循环并添加点击事件,所以当我们点击一​​个项目时,我们将获得特定的数据,然后我们解析它,以便我们可以将它用作对象,例如我们在div元素中将项目的特定数据作为字符串打印(“display -data“id)on click event:

(function(){ 
    var item = [], item_data = '', item_data_obj = {}, display = {}; 
    document.addEventListener('DOMContentLoaded', function(){ 
     display = document.getElementById('display-data'); 
     item = document.getElementsByClassName('post'); 
     for (let i = 0; i < item.length; i++){ 
      item[i].addEventListener('click', function(){ 
       item_data = this.getAttribute('data-other'); 
       item_data_obj = JSON.parse(item_data); 
       display.innerHTML = this.innerHTML + ' :' + item_data; 
      }) 
     } 
    }) 
})()