繁体   English   中英

如何在jQuery JSON中访问HTML元素属性

[英]How to access HTML element attribute in jQuery JSON

我正在尝试访问特定的HTML元素属性,并将其分配给JSON属性。

首先,我从文件中获取JSON对象并将其加载到设置中 然后,我遍历行并创建具有各种属性的文本输入。

由于我使用的是Iris插件,因此我马上就将其触发。 您会看到我正在使用changeElements函数,其中使用了iris-id (有效)。

所以问题是...为什么虹膜部分的颜色属性为空?

function startCorr(jsonFile) {
    request = new XMLHttpRequest();
    request.open('GET', jsonFile, true);
    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            settings = JSON.parse(request.responseText);
            $.each(settings, function(key, jsonRow) {
                $(sidePanel).append(createInput(key, jsonRow));
            });
            // iris
            $('.iris').iris({
                color: $(this).attr("iris-color"), // doesn't work
                width: 200,
                border: false,
                hide: false,
                change: function(event, ui) {
                    changeElements($(this).attr("iris-id"), ui);
                }
            });
        } else {
            console.log("Error getting JSON file");
        }
    };
    request.send();
}

function createInput(key, jsonRow) {
    input  = "<label>" + jsonRow.name + "<input type='text' class='iris' id='" + jsonRow.section + "' ";
    input += "iris-color='" + getColor(jsonRow.selectors[0]) + "' iris-id='" + key + "'>";
    input += "</label>"

    return input;
}

function getColor(selectorObject) {
    return $(selectorObject.selector).css(selectorObject.style);
}

JSON格式

[
  {
    "name": "Global text",
    "section": "text-global",
    "input": "color",
    "selectors": [
      {
        "selector": ".button.special",
        "style": "background-color"
      },
      {
        "selector": ".button.notSoSpecial",
        "style": "color"
      }
    ],
    "areas": ["homepage", "detail", "category", "basket"]
  },
  {
    "name": "Text on hover",
    "section": "text-hover",
    "input": "color",
    "selectors": [
      {
        "selector": "#banner p",
        "style": "color"
      }
    ],
    "areas": ["homepage", "detail", "category", "basket"]
  }
]

当您需要访问特定于元素的数据以传递到插件的选项时,一种非常常见的方法是在$.each循环内初始化插件。 在循环中, this是当前元素

$('.iris').each(function() {
  var $el = $(this);
  $el.iris({
    color: $el.attr("iris-color"), 
    width: 200,
    border: false,
    hide: false,
    change: function(event, ui) {
      changeElements($el.attr("iris-id"), ui);
    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM