1

我只需要通过 RegExp 从给定字符串中获取所有属性和文本,如果可以使用一行 RegExp 那就太好了。我想从字符串中获取每个属性,如果它在 " 或 ' 或独立的。

  • 属性:value = "1" or value = '1' or value="1" or value='1' or value=1 or value=""
  • 属性:readonly or disabled

我试过了,但这对我不起作用。

var s = '<option value="1" data-foo="Foo" readonly>Value 1</option>', m
m = s.match(/<option ([^>]*)>(.*)<\/option>/)
console.log(m)
// gives ["<option value="1" data-...adonly>Value 1</option>", "value="1" data-foo="Foo" readonly", "Value 1"]

非常感谢。

4

3 回答 3

2

为什么不直接创建元素?

var s = '<option value="1" data-foo="Foo" readonly>Value 1</option>'​​​​​;

var test_element = document.createElement('div');
test_element.innerHTML = s;

var element = test_element.childNodes[0];
​var attributes = element.attributes;

for (var i = 0; i < attributes.length; i++) {
    var attribute = attributes[i];

    console.log(attribute.name, '=>', attribute.value);
}​

输出:

value => 1
data-foo => Foo
readonly =>  

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

于 2012-12-14T08:19:13.320 回答
0

我相信以下正则表达式可以获取您想要的内容(好吧,看起来确实很丑,但是)

s.match(/<option\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*\s*([^\s\=]*)\s*\=*\s*([^\s\=]*)*>(.*)<\/option>/);

对于s = '<option value="1" data-foo="Foo" readonly>Value 1</option>',它返回:

[
  "<option value="1" data-foo="Foo" readonly>Value 1</option>", // s itlsef
  "value", // first attr
  ""1"", // value as written in s (with double quotes)
  "data-foo", // second attr
  ""Foo"", // value as written in s (with double quotes)
  "readonly", // third attr
  undefined, // no value specified for readonly, so undefined
  "Value 1" // the option text
]
于 2012-12-14T08:26:47.713 回答
0

实际上我需要这个来用更简单的方式处理“选项”元素,更简单的正则表达式。innerHTML = append content如果用于select元素,则 ie 的 Cos 不会附加。附加操作在下面的链接中提到,但不适用于选项元素。然后我找到了解决这个问题的方法。如果追加内容是选项或选项,则使用handleOptionElements,如果不使用asyncInnerHTML

function append(el, child) {
    if (child.nodeType === 1 || child.nodeType === 3) {
        // Without clone, removes element if it is copied from document
        return el.appendChild(child.cloneNode(true));
    }

    content = trim(content);
    if (content.substring(0, 7) === "<option" && 
            content.substring(content.length - 7) === "option>") {
        handleOptionElements(content, el);
    } else {
        el.innerHTML = content;
    }

    return el;
}

http://james.padolsey.com/javascript/asynchronous-innerhtml/
为 innerHTML 设置大值时提高性能的方法

var re_standaloneAttributes = /^(select|disabl)ed$/i,
    re_optionSearch = /<option\s*([^>]*)>(.*?)<\/option>/gi,
    re_attributeSearch = /([^\s]*)=["'](.*?)["']|([\w\-]+)/g;

function handleOptionElements(content, targetElement) {
    var options = [], attributes = [],
         optionElement, optionElements = [], createOption;

    (""+ content).replace(re_optionSearch, function(src1, attr, text) {
        if (!src1) return;
        (""+ attr).replace(re_attributeSearch, function(src2, name, value) {
            if (!src2) return;
            name = name || src2;
            value = value || (value = re_standaloneAttributes.test(name) ? name : "");
            attributes.push({name: name, value: value});
        });
        options.push({text: text || "", attributes: attributes});
        // Reset attributes for each element
        attributes = [];
    });

    createOption = (function() {
        var option = document.createElement("option");
        return function() { return option.cloneNode(true) };
    })();

    forEach(options, function(option) {
        optionElement = createOption();
        // optionElement.text doesn't work on ie 7-8
        optionElement.textContent = optionElement.innerText = option.text;
        forEach(option.attributes, function(attribute) {
            optionElement.setAttribute(attribute.name, attribute.value);
        });

        if (targetElement !== undefined) {
            targetElement.appendChild(optionElement);
        } else {
            optionElements.push(optionElement);
        }
    });

    return optionElements;
}
于 2012-12-16T02:54:05.247 回答