2009-11-04 61 views
1

我有一些jquery代碼,我試圖翻譯成YUI。我正在使用YUI 2.8。使用jQuery我可以輕鬆地替換一個DOM元素。有沒有一種很好的方式來使用YUI來代替jquery.replaceWith和jquery.append。我試着寫下如下的函數,但是這些只能傳文本,而我需要傳遞一個渲染的dom。 <p><a href="">what</a></p>(比這要複雜得多)YUI替換jQuery.replaceWith和jquery.append

function replaceWith(el_id, text){ 
    //YUI doesn't seem to have a good replacement for $.replaceWith. Writing one to simulate it for my usages. 
    node_to_replace = YAHOO.util.Dom.get(el_id); 
    if(node_to_replace){ 
    new_node = document.createTextNode(text); 
    YAHOO.util.Dom.insertAfter(new_node, node_to_replace); 
    node_to_replace.innerHTML = '' 
    } 
    return node_to_replace 
} 

function append(el_id, text){ 
    //YUI doesn't seem to have a good replacement for $.append. Writing one to simulate it for my usages. 
    node_to_replace = YAHOO.util.Dom.get(el_id); 
    if(node_to_replace){ 
    new_node = document.createTextNode(text); 
    YAHOO.util.Dom.insertAfter(new_node, node_to_replace); 
    } 
    return node_to_replace 
} 

回答

1

試試這個:

function replaceWith(el_id, text){ 
    var node_to_replace = YAHOO.util.Dom.get(el_id); 
    if(node_to_replace){ 
     var new_node=document.createElement("div"); 
     new_node.innerHTML=text; //Parse the code inside a new element 
     var beforeNode=node_to_replace; 
     for(i=0;i<new_node.childNodes.length;i++){ 
      //Move generated children after the replaced node 
      YAHOO.util.Dom.insertAfter(new_node.childNodes[i], beforeNode); 
      beforeNode=new_node.childNodes[i]; 
     } 
     node_to_replace.parentNode.removeChild(node_to_replace);//Remove the replaced element 
    } 
    return node_to_replace 
} 

function append(el_id, text){ 
    var node_to_replace = YAHOO.util.Dom.get(el_id); 
    if(node_to_replace){ 
     var new_node=document.createElement("div"); 
     new_node.innerHTML=text; //Parse the code inside a new element 
     for(i=0;i<new_node.childNodes.length;i++){ 
      //Move generated children inside the node 
      node_to_replace.appendChild(new_node.childNodes[i]); 
     } 
    } 
    return node_to_replace 
} 
1

這似乎是爲我工作:

function replaceWith(id, innerHTML) { 
var oldNode = YAHOO.util.Dom.get(id); 
var newNode = document.createElement(oldNode.tagName); 
newNode.id = id; 
newNode.innerHTML = innerHTML; 
YAHOO.util.Dom.get(id).parentNode.replaceChild(newNode, oldNode); 
return YAHOO.util.Dom.get(id); 
} 

function append(id, appendedText) { 
var elem = YAHOO.util.Dom.get(id); 
elem.innerHTML += appendedText; 
return elem; 
}