【问题标题】:Get attribute values with JQuery issue (Uncaught TypeError: Cannot use 'in' operator to search for 'length' in..)使用 JQuery 问题获取属性值(未捕获的 TypeError:无法使用 'in' 运算符搜索 'length' in..)
【发布时间】:2016-05-12 02:45:35
【问题描述】:

我正在尝试使用 JQuery 获取属性值,但出现错误:jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in PROD

我看到了一些关于将 JQuery 版本降级到 1.10.xx 的建议,但我在所有版本的 JQuery 中都收到此错误。

你有什么建议吗?

提前谢谢..

我的代码如下:

<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>

<body>
    <input test="PROD" value="2" type="text">
    <input test="DEV"  value="3" type="text">
    <input type="button" value="Write It" onclick="writeIt()"/>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
function writeIt() {
    $.each($('input').attr('test'), function () {
        var testdata = $(this).attr('test');
        //$(this).val(testdata);
        console.log(testdata);
    });

}
</script>

【问题讨论】:

    标签: jquery attributes


    【解决方案1】:

    你可以试试

    <script>
    function writeIt() {
        $('input:not([type="button"])').each(function () {
            var testdata = $(this).attr('test');
            //$(this).val(testdata);
            console.log(testdata);
        });
    
    }
    </script>
    

    演示

    function writeIt() {
        $('input:not([type="button"])').each(function () {
           var testdata = $(this).attr('test');
           //$(this).val(testdata);
           console.log(testdata);
        });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input test="PROD" value="2" type="text">
    <input test="DEV"  value="3" type="text">
    <input type="button" value="Write It" onclick="writeIt()"/>

    【讨论】:

    • 非常感谢您的回答。在您回答之后,我将代码更改为 code $("input[test]").each(function () { var testdata = $(this).attr('test'); //$(this ).val(testdata); console.log(testdata); }); code 并且它工作正常。你能解释一下我的代码中有什么错误吗?
    • @Grcn 使用 .each 到 $('input').attr('test') 的错误方式 .. 你需要对象循环然后从中获取 attr() ..你也可以试试 $.each($("input[test]")).. 你的 $("input[test]") 选择器也很好..祝你好运:)
    • 再次非常感谢你 :) @Mohamed
    猜你喜欢
    • 2014-07-09
    • 2015-04-15
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2018-01-10
    • 2019-10-10
    相关资源
    最近更新 更多