变量不传递给其他函数
Variable not passing to other functions
我有一张桌子。 当用户单击表单元格时,jquery 会获取单元格内的子项(输入标记)的 id 属性和名称属性。 当我提醒各个变量时,它们会正确发出警报。 但是,当我将值返回到数组并提醒它们我在脚本中遇到问题的其他位置时。例如,当我提醒另一个函数中的值时,我得到[对象HTMLTableCellElement]。
我已经在 document.ready 之后在脚本顶部的任何函数之外声明了 id 和 name 变量。 为什么无法将 id 和名称的正确值获取到另一个匿名函数或函数中。
<script>
$(document).ready(function() {
var id = 0;
var name = 0;
var values2 = [];
//when a table cell is clicked
values2 = $('table tr td').click(function() {
//grab the id attribute of the table cell's child input tags that have a class of hidden
id = $(this).children("input[class='hidden']").attr("id");
alert( id ); //<----- alerts id properly (output for example is 25)
//grab the name attribute of the table cell's child input tags that have a class of hidden
name = $(this).children("input[class='hidden']").attr("name");
alert( name ); //<----- alerts id properly (output for example is firstinput)
return [id , name]; //<------ here is where I try to return both these values in to an array
// so that I can use the values else where in the script. However
// I am not able to use the values
});
$( "#nameForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
alert(values2[0]); // <----alerts [objectHTMLtableCellElement]
//this should alert ID
var posting = $.post( "comments.php", $('#nameForm').serialize(), function(data) {
$('#result').html(data);
});
return false;
// $('#result').html(term);
});
});
</script>
而不是
values2 = $('table tr td').click(function(){
return [id , name];
});
用
$('table tr td').click(function(){
values2 = [id , name];
});
values2 = $('table tr td').click(function() {
当你把一个函数传递给click
时,你说的是"点击这个函数时,调用这个函数"。
然后,调用函数继续。
click()
的返回值不是运行传递给 click 的函数的结果。
如果要使用这些值来响应单击,则需要在传递给单击的函数(或它调用的函数)中执行此操作。
如果要将它们存储为全局以供以后使用,则需要将它们分配给传递给单击的函数中的全局,而不是作为返回值。
相关文章:
- 对其他函数使用匿名函数's参数
- 创建要在其他函数中使用的全局变量
- 在Jquery调用之间添加其他函数
- Mocking console.log()/MOCHA测试框架中的任何其他函数
- 如何从ipify函数返回ip地址,以便在其他函数中使用
- 如果没有其他函数链接到promise,则默认行为
- Javascript创建函数,以便在其他函数之间共享变量
- 使通过函数加载的JSON可用于其他函数
- 可以获取模板实例值,但不能将其用于其他函数
- 如何停止一个函数并将其他函数设置为在 html5 的 javascript 中加载时运行
- 这个关键字位于$.ajax()中,用于调用其他函数来设置url
- SQLite+Javascript:在每个其他函数中执行多个查询
- 调用geocomplete中的其他函数
- 如何在 javascript 中将变量传递给对象内的其他函数
- 如何在Javascript中创建一个调用其他函数的函数
- 我用脚本创建了一个按钮.我可以通过点击按钮调用其他函数吗?我这样做,但失败了
- AJAX请求返回Javascript获胜't返回特定函数,但将返回其他函数
- 如何在其他函数中使用fn作为函数参数
- 返回带有其他函数的变量
- 如何在ES6中使用Arrow函数引用对象内部的其他函数