单击不调用JS函数(在任何浏览器上)

onclick not calling JS function (on any browser)

本文关键字:任何 浏览器 调用 JS 函数 单击      更新时间:2023-09-26

示例:

<button id="banButton{$id}"onclick="deletePhoto({$id}, {$picture_path});">BAN {$id}</button>

</body>标签之前:

<script type="text/javascript" src="../profile/theme/js/jquery.js"></script>
<script type="text/javascript">
function deletePhoto(id, pic_path) {
    alert("test");
    $.post("ajax.php", { toid: toid, pic_path: pic_path });
}
$(document).ready(function() {
    alert("test2");
});

</script>

呈现的 HTML 可能如下所示:

<button id="banButton508" onclick="deletePhoto(508, profile_photos/686733/1_4044.jpg);">BAN 508</button> <img src="../profile/pics/686725/2_3234.jpg" width="150" height="150"/>

加载页面时会显示"test2"警报,但单击按钮时,该功能不会运行(警报甚至不显示(。

知道为什么吗?

编辑:我现在用引号将picture_path括起来,例如

<button id="banButton{$id}" class="banButton" onclick="deletePhoto({$id}, "{$picture_path}");">BAN {$id}</button>

仍然没有解决这个问题。

看起来picture_path是一个字符串文字,如果id值也是一个字符串,那么也用''括起来

<button id="banButton{$id}" onclick="deletePhoto('{$id}', '{$picture_path}');">BAN {$id}</button>

尝试将函数与其他所有内容一起放在文档就绪函数中。

$(document).ready(function(){
function deletePhoto(id, pic_path) {
    alert("test");
    $.post("ajax.php", { toid: toid, pic_path: pic_path });
}
});

以下代码工作正常

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>Test</title>
  </head>
<body>
<button id="banButton508" onclick="deletePhoto(508, 'profile_photos/686733/1_4044.jpg');">BAN 508</button> <img src="../profile/pics/686725/2_3234.jpg" width="150" height="150"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">
function deletePhoto(id, pic_path) {
alert("test"+pic_path);
$.post("ajax.php", { toid: toid, pic_path: pic_path });
}
$(document).ready(function() {
  alert("test2");
});

</script>
 </body>

如果你使用的是jquery,那么为什么不应该以标准形式操作dom-aciton。

喜欢

<button id="banButton{id}" data-id="{id}" data-image_url="{$picture_path}">BAN {id}</button>

和JavaScript

function deletePhoto(id, pic_path) {
    alert("test");
    $.post("ajax.php", { toid: toid, pic_path: pic_path });
}
$(document).ready(function() {
    alert("test2");
    $("button[id^='banButton']").click(function(){
        var id = $(this).data('id');
        var img_url = $(this).data('image_url');
        deletePhoto(id, img_url);
    });
});