jQuery中.parent().children()用法疑问:返回[Object Object]如何解决?
问题分析与解决方案
你遇到的[Object Object]提示,本质是两个小问题导致的:选择器写法错误,以及直接alert了jQuery对象本身而非它的实际值/属性。
1. 核心问题:选择器使用错误
你的代码里$(this).parent().children('depnum-'+fileLocation)的写法不对——depnum-xxx是元素的id,jQuery中选择id必须加#前缀,正确的选择器应该是#depnum-'+fileLocation,depdate的选择逻辑同理。
2. 为什么会显示[Object Object]?
当你直接alert一个jQuery对象时,浏览器会默认输出它的字符串化形式[Object Object]。如果要获取输入框的内容,需要调用.val()方法;如果要查看DOM元素本身,可以用.get(0)或者[0]把jQuery对象转成原生DOM对象。
修改后的完整代码
<div> <input name='input1' id='src-1' value='input1' type='checkbox'/> <br /> <input name='depnum1' id='depnum-1' value='测试金额' type='text'/> <br /> <input name='depdate1' id='depdate-1' value='2024-05-20' type='text'/> </div> <script> $(document).ready(function() { $("#SubDeposit").click(function(){ $('input[type=checkbox]').each(function (){ if($(this).prop('checked')) { // 简化fileLocation的获取逻辑 var fileLocation = $(this).attr('id').substring(4); alert(fileLocation); // 修正选择器,添加#前缀 var depnum = $(this).parent().children('#depnum-'+fileLocation); var depdate = $(this).parent().children('#depdate-'+fileLocation); // 正确alert输入框的值 alert(depnum.val()); alert(depdate.val()); // 控制台可以同时查看对象和值,方便调试 console.log("depnum jQuery对象:", depnum); console.log("depnum 输入值:", depnum.val()); console.log("depdate jQuery对象:", depdate); console.log("depdate 输入值:", depdate.val()); } }); }); }); </script>
额外优化建议
- 变量声明记得加
var(你原代码里的depnum和depdate没加,会变成全局变量,容易引发冲突) - 同层级元素可以用
siblings()替代parent().children(),逻辑更直观:var depnum = $(this).siblings('#depnum-'+fileLocation); var depdate = $(this).siblings('#depdate-'+fileLocation);
内容的提问来源于stack exchange,提问作者Liam
相关产品推荐
相关产品推荐

