[英]Passing Value to Javascript function
I'm calling a jQuery function, but the alert function displays [object Object]. 我正在调用jQuery函数,但是Alert函数显示[object Object]。 The check value works, but not the passed id value. 检查值有效,但传递的id值无效。
Here's the call to the function taken from the html output: 这是从html输出中获取的对该函数的调用:
<td class="myGroups">
<input class="chkSubscribed" type="checkbox" onclick="UpdateSubscription(2)" name="subscribed">
</td>
Here's the javascsript function: 这是javascsript函数:
$(".chkSubscribed").change(function(id) {
alert(id);
var chkd=0;
var groupid=id;
if (this.checked) { chkd=1; }
$.ajax({
type:"POST",
url:"resources/updateSubscribe.php",
data: { group_id: groupid, checkval: chkd },
success: function(){
alert("Account updated!" + "chkval=" + chkd + " id=" + groupid); }
});
});
Thanks for any help! 谢谢你的帮助!
There are a few different issues at play here. 这里有几个不同的问题。
alert()
for debugging. 使用alert()
进行调试。 This is almost always worse than using console.log()
. 这几乎总是比使用console.log()
更糟糕。 Everything passed to alert
is converted to a string, which is why you see "[object Object]"
instead of something useful. 传递给alert
所有内容都转换为字符串,这就是为什么看到"[object Object]"
而不是有用的东西的原因。 Switch to console.log()
and you'll see something meaningful. 切换到console.log()
,您将看到一些有意义的东西。 event
object . jQuery事件回调传递给jQuery event
对象 。 That object is what id
is set to. 该对象是id
设置的对象。 onclick
handler has absolutely nothing to do with the change
handler that you've bound with jQuery. 内联onclick
处理程序与与jQuery绑定的change
处理程序完全无关 。 You're doing it wrong. 你这样做是错的。
Either you want to call a function or you want to use the change event. 您要调用函数还是要使用change事件。
If you want to call a function create a function as follows: 如果要调用函数,请按如下方式创建一个函数:
function moo(id) {
//code here
}
If you want to do it using the change event you can give your input an id of the number you want as follows: 如果要使用change事件来执行此操作,则可以为输入提供所需编号的ID,如下所示:
<input id="2" class="chkSubscribed" type="checkbox" name="subscribed">
And then your javascript should look as follows: 然后,您的JavaScript应该如下所示:
$(".chkSubscribed").change(function() {
id=this.id;
//and the rest of the code as you wrote
});
jQuery函数change()
将传递事件对象,而不是更改后的对象的ID-您将其视为当前的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.