【问题标题】:jquery get attr value from arrayjquery从数组中获取attr值
【发布时间】:2015-10-31 14:30:27
【问题描述】:
var t=new Array('title','placeholder','alt');

$.each(t,function(k,v){
    alert(typeof $(this).attr(v));//PROBLEM $(this) is not the right object
});

目标: 获取存在的属性(标题或占位符或替代)值。

如果元素有标题,则返回标题,如果没有,检查占位符,然后是alt。

例如:

>> var v='title';
>> $(this).attr(v);
>> $(this).attr('title');(I want this)

旧解决方案:

for(var i=0;i<t.length;i++){
    alert($(this).attr(t[i]));
}

真正的解决方案:感谢 mplungjan

var o=$(this);
$.each(t,function(k,v){
    alert(typeof o.attr(v));//PROBLEM $(this) is not the right object
});

【问题讨论】:

  • 因为 Array 中没有 attr 且 v 不是 jQuery 对象 - alert(typeof v);

标签: jquery each attr


【解决方案1】:

这就是我相信你正在尝试做的事情。

单击该字段并在控制台中查看

$(function() {
  var t=['title','placeholder','alt'];
  $("input").on("focus",function() { // we need an event 
    var inp = $(this); // the input as a jQuery object
    $.each(t,function(_,key) { // in here, $(this) is NOT the input
      console.log(key+":"+inp.prop(key)); // we use prop instead of attr
    });
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inp1" type="text" title="Some input field" placeholder="Enter some text" />

【讨论】:

    【解决方案2】:

    试试这个..

    $.each() 函数与 $(selector).each() 不同,后者用于以独占方式遍历 jQuery 对象。 $.each() 函数可用于迭代任何集合,无论是对象还是数组。在数组的情况下,回调每次都会传递一个数组索引和一个对应的数组值。 (该值也可以通过 this 关键字访问,但 Javascript 将始终将 this 值包装为一个 Object,即使它是一个简单的字符串或数字值。)该方法返回其第一个参数,即被迭代的对象。

    $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
    });
    

    http://api.jquery.com/jquery.each/

    您的代码

    var t=new Array('title','placeholder','alt');
    
        $.each(t,function(k,v){
            alert("key:"+k+"value:"+v);
        });
    

    演示:http://jsfiddle.net/so2pp1tp/

    【讨论】:

    • 对不起,我的目标是获取属性值,使用数组中的名称,问题是 attr 函数不起作用。无法获得价值,但只能获得“未定义”
    • 你想要像“title”这样的html动态属性吗?
    • 如果元素有title,则返回title,如果没有,检查占位符,然后alt。返回任何存在的属性
    • 发布您的示例 html
    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多