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

How to access HTML element attribute in jQuery JSON

本文关键字:访问 HTML 元素 属性 JSON jQuery      更新时间:2023-09-26

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

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

由于我使用的是虹膜插件,所以我会立即触发它。你可以看到我正在使用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);
}

杰伦

[
  {
    "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);
    }
  });
});