使用来自不同HTML属性的项填充数组

时间:2015-12-17 00:12:17

标签: javascript jquery html arrays

我有大约1000张图片和textareas,它们具有相同的类名和自定义属性。类名分别是表情符号和表情符号列表。自定义属性分别是emo-tag和emo-as​​cii。

每个图片都有自己的合作伙伴(te​​xtarea),其自定义属性中的内容完全相同。

示例:

emo-tag   = "f-x" // for images
emo-ascii = "f-x" // for textareas

其中x表示0到999之间的数字。

我的脚本捕获图像属性和我需要的没有问题。当我尝试获取具有类似图像的确切属性内容的textarea的值时,问题就开始了。

这是我的代码:

$(function(){
var json = [];

$('img').each(function(){
    var emoimg  = $(this).attr("src");
    var emoalt  = $(this).attr("alt");
    var emotag  = $(this).attr("emo-tag");

    //Does not this supposed to capture the value of this specific textarea?
    var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();

        json.push({
            id : emotag,
            name : emoalt,
            img : emoimg,
            content: emoascii       
        });

});
  var s = JSON.stringify(json);
  $("#content").after("<div>" + s + "</div>");
});

就像我说的那样,代码可以工作但是捕获并推入数组的textarea只是第一个和数组的所有项目。我怎样才能完成我想要的东西?

当前输出:

[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":)"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":)"},
...
...
...
]

期望输出:

[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":D"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":("},
...
...
...
]

1 个答案:

答案 0 :(得分:3)

使用$('.emoticonlist').attr("emo-ascii",emotag),您需要设置属性,而不是获取属性等于emotag的元素。(http://api.jquery.com/attr/

也许尝试更换一行

var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();

var emoascii= $('.emoticonlist[emo-ascii=' + emotag +']').val();

https://api.jquery.com/attribute-equals-selector/