在后面的代码中,我有以下代码从 SQL 数据库获取 [IDphoto]。现在我想将 IDphoto 作为参数发送给 jQuery 函数 onClick。我怎样才能做到这一点?
隐藏代码
sb.AppendFormat("<a onclick='popup()' href='#" + IDphoto + "'>");
jQuery
function popup() {
$(document).ready(function () {
// Here I want to get the value of IDphoto ...
});
}
更新
我已经根据 TrueBlueAussie 回复更新了代码:
photos_sb.AppendFormat("<a href=\"#\" class=\"photo\" data-photo=\"" + IDphoto + "\">");
$(document).ready(function () {
// Here I want to get the value of IDphoto ...
$('a.photo').click(function(e){
// Stop the link click from moving to the page top
e.preventDefault();
var id = $(this).attr("data-photo");
alert(id);
});
});
什么也没发生。单击不会触发 jQuery 函数!
最佳答案
几点建议:
- 不要在 jQuery 中使用内联
onclick
属性处理程序。这增加了不必要的复杂性以及事件代码与事件注册代码的分离。 - 对 HTML 属性值使用双引号。大多数浏览器都接受其中之一,但双引号对于兼容性来说更安全。
- 还可以使用
data-
属性来提供元数据(而不是将其隐藏在 href 中)。将 href 设为普通书签链接 (#)。 - 在任何照片链接上使用通用类以允许更简单的 jQuery 匹配(和样式):
$(function(){...});
是$(document).ready(function(){...}); 的便捷快捷方式;
例如sb.AppendFormat("");
并添加一个 jQuery 点击处理程序来查找对任何 .photo
链接的点击:
$(function () {
// Here I want to get the value of IDphoto ...
$('a.photo').click(function(e){
// Stop the link click from moving to the page top
e.preventDefault();
var id = $(this).attr("data-photo");
alert(id);
});
});
这是使用一些示例链接的上述模型:
关于javascript - 从代码隐藏向 jQuery 函数发送动态参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27899079/