HTML onclick函数不会通过PHP echo调用

时间:2016-06-20 22:46:50

标签: javascript php jquery html

最初,我有以下内容使用PHP生成菜单:

$hold = "select id, email from info";
$h = mysqli_query($connection,$hold);
$a = array();

while($row = mysqli_fetch_array($h)){
    $a[ $row['id'] ] = $row['email'];
    //    key             value
}

我在一个被html包围的index.php页面中有这个代码。是从数据库中的项目生成菜单。在这种形式下,它运行良好,并称为“myFunction(string)'这是一个单独的global.js文件。

$a[d] = $row['email'];      // d is an undefined constant
$a[$d] = $row['email'];     // value of $d will be used as key (0, 1, 2, etc.)
$a['d'] = $row['email'];    // literal letter 'd' will be used as key (repeatedly)
$a[] = $row['email'];       // PHP automatically assigns incrementing numeric keys (0,1,etc.)

getContent.php类似于上面的php。除了它在查询中使用where子句,它从字符串中提取。

所以当我去清理产生菜单的代码时出现了问题。 我将以下函数添加到global.js

<ul>
   <?php 
         $items = mysqli_query($con, "SELECT DISTINCT item FROM table");
         while ($row = mysqli_fetch_array($items)) { ?>
             <li><a href='#' onclick='myFunction(<?php echo $row['item'] ?>)'><?php echo $row['item'] ?></a></li><? php 
         } ?>
</ul>

getMenu.php看起来像这样:

function myFunction(string) {
$('#container').load('php/getContent.php', {string: string});
}

除了onclick功能不再有效之外,这在生成菜单项时也能正常工作。 放置匿名内联onclick函数确实有效,所以我认为它可能是global.js文件中的$(document.ready()导致问题。我将$(document).ready()移回到index.php中脚本标签要检查,仍然无法正常工作。

我最初将脚本标记作为正文中的最后一个元素,因此我将它们移动到标题中以检查是否有任何改变,但这也没有用。

标头标签如下所示:

$(document).ready(function() {
    $('#menu').load('php/getMenu.php');
});

我所有的php文件都在一个名为php的子文件夹中,所有我的js文件都在一个名为scripts的子文件夹中。

首先,如果我在一个带有其他函数的js文件中有$(document).ready(),那会不会有问题呢?

其次是关于为什么函数不再被调用的任何想法?

先谢谢。

1 个答案:

答案 0 :(得分:0)

这也是我遇到的问题。在DOM完全加载后生成元素时onclick将不再工作。 就我而言,我用过:

$('parent of element which is in DOM').delegate('element', 'event', function(){
});

并且工作了。

查看jQuery API http://api.jquery.com/delegate/

在你的情况下,你的php应该是:

$items = mysqli_query($con, "SELECT DISTINCT item FROM table");

echo "<ul class='tab'>";
while ($row = mysqli_fetch_array($items) {
    echo '<li><a href="#">'.$row['item'].'<input class="sql_input" hidden="hidden" value="'.$row['item'].'"></a></li>';
}
echo '</ul>';

和你的Javascript:

function load_file(value){
   $('#container').load('php/getContent.php', {string: value});
}

$('parent of .tab').delegate('.tab li a', 'click', function(){
   var get_value = $(this).find('.sql_input').val();
   load_file(get_value);  
});