使用jQuery获取未知数据属性并将它们复制到新元素

时间:2014-04-16 23:03:55

标签: javascript jquery html

我正在尝试通过将标准表单选择转换为<li>列表来创建自定义下拉列表选择样式,但是我需要为每个-data添加一些<option>属性需要复制到<li>

问题在于我并不总是知道这些数据属性会被调用,因此我想要一种只将<option>标记中的任何数据属性复制到<li>标记的方法。 / p>

我目前的代码如下:

原始<option>代码...

<option data-somedata="something" data-else="something else" value="some value">Hello</option>

和jQuery ......

jQuery('.fancy-select .field option').each(function(){
  jQuery(this).parents('.fancy-select').find('ul').append('<li><a href="">' + jQuery(this).text() + '</a></li>')
});

有没有办法将所有数据属性从我的选项标签复制到<li>标签,而无需按名称指定?

3 个答案:

答案 0 :(得分:3)

自从我使用jQuery以来已经有一段时间了,但我的第一个想法是查看属性,寻找&#34;数据 - &#34;那些。

类似的东西:

jQuery('.fancy-select .field option').each(function(){
    var $li = jQuery( '<li><a href="">' + jQuery(this).text() + '</a></li>' );
    jQuery.each( this.attributes, function ( item ) {
        if ( item.name.substring(0,6) === "data-" ) {
            $li.attr( item.name, item.value );
        }
    } );

    jQuery(this).parents('.fancy-select').find('ul').append( $li );
});

一个快速的Google表明,如果你使用更新版本的jQuery,data()可能会使这段代码变得更加简单 - https://api.jquery.com/jQuery.data/

jQuery('.fancy-select .field option').each(function(){
    var $li = jQuery( '<li><a href="">' + jQuery(this).text() + '</a></li>' );
    jQuery.each( jQuery(this).data(), function ( key, value ) {
        $li.data( key, value );
    } );

    jQuery(this).parents('.fancy-select').find('ul').append( $li );
});

答案 1 :(得分:1)

只需clone the node

jQuery('.fancy-select .field option').each(function(){
    this.parentNode.appendChild(this.cloneNode());
});

由于这是vanilla,并且DOM操作而不是字符串操作,因此速度会快得多。而且它也很简单。

Fiddle

但您希望它是<li>,而不是<option>?您可以更改outerHTML,但更快的方法是:

jQuery('.fancy-select .field option').each(function() {
    var newNode = document.createElement('li');
    for (var i = this.attributes.length - 1; i--;) {
        newNode.attributes.setNamedItem(this.attributes[i].cloneNode());
    }
    this.parentNode.parentNode.appendChild(newNode);
});

不是克隆整个节点,而是进行昂贵的outerHTML替换,而只是逐个复制属性!

Fiddle

答案 2 :(得分:1)

试试这个(模式)

html(例如)

<ul class="selections">
    <select>
        <option data-somedata="something" data-else="something else" value="some value">abc</option>
        <option data-somedata="something other" data-else="something else other" value="some value">def</option>
    </select>
</ul>

JS

function optdata(selector, container, el) {
    $.each($(selector), function (index, value) {
        $(container).append(
        $(el).html("<a href=''>" + $(value).html() + "</a>")
        .data($(value).data()) 
        );
        return (index != $(value).size())
    });
};
optdata($("option"), $(".selections"), "<li>");

jsfiddle http://jsfiddle.net/guest271314/9NvJm/

相关问题