0

nodeNameを使用してノード名を取得できることは知っていますが、jqueryを使用してnodeNameを設定することもできますか?基本的に、ノード名の大文字と小文字を大文字から小文字に変更したかったのです。

どうもありがとう

4

2 に答える 2

3

これを適切に行うには、ここで説明するようにそのタグを置き換える必要があると思います: jQuery:タグ名を変更する方法は?

残念ながら、これにはタグ名だけでなく要素全体を置き換える必要があるため、タグ名を置き換える場合は、タグの属性とその中のコードの両方を保持する方法を見つける必要があります。

幸い、数分余分に時間があったので、それを実行する関数を作成しました。

function change_tag_name(selector,tagname){
    var old_elm = $(selector);
    //Create a jquery element based on selector
    var original_elements = old_elm.get();
    //Get the array of original dom objects
    //Note: We get the original dom objects because jQuery objects do not provide access to the attributes array
    for(var i=0; i< original_elements.length; i+=1){
        var original_element = original_elements[i];
        //Create reference to original element in dom
        var new_elm = $(document.createElement(tagname));
        //Create new element with desired tagname
        new_elm.html($(original_element).html());
        //Add original element's inner elements to new element

        var original_attributes = original_element.attributes;
        //Create an array of the original element's attributes;
        var attributes = new Object();
        //Create a new generic object that will hold the attributes for the new element

        for(var j=0; j<original_attributes.length; j+=1){
            var attribute = original_attributes[j];
            var name = attribute.nodeName;
            //Note: The attributes "nodeName","localName",and "name" appear to have the same value, so I just chose one. It's entirely possible that these could have different values in different contexts...
            //var name = attribute.localName;
            //var name = attribute.name;
            var value = attribute.nodeValue;
            //Note: The attributes "nodeValue","textContext",and "value" appear to have the same value, so I just chose one. It's entirely possible that these could have different values in different contexts...
            //var value = attribute.textContext;
            //var value = attribute.value;
            attributes[name]=value;
        }
        //Populate attributes object
        new_elm.attr(attributes);
        //Assign attributes from old element to new element        
        $(original_element).replaceWith(new_elm);
        //Replace old_element with new element 
    }
}

また、属性が元の順序であることを保証する方法はないと思います。

于 2012-11-29T00:32:00.683 に答える
0

nodeNameを変更することはできませんが、別の名前で新しいノードを作成し、属性をコピーしてから、一方を他方に置き換えることはできます。

jQueryを使用すると、属性とプロパティを区別するのが難しくなります。IE独自のouterHTMLプロパティ(他のいくつかのブラウザでサポートされています)と文字列操作を使用できる場合がありますが、これは一般にWebでは機能しません。

そのようなノードが多数ある場合は、「

于 2012-11-28T23:35:37.710 に答える