2015-09-10 23 views
-1

我正在處理一個簡單的項目,該項目需要使用某些邏輯修改html源代碼,然後將修改後的html源代碼顯示一個按鈕被點擊時的div。使用Javascript或jQuery更改html源代碼,然後將更改後的源代碼顯示在文本區域中

修改前的輸出是當我點擊查看HTML enter image description here

當我點擊顯示轉換的HTML輸出類似 enter image description here

我基本上想要做內兒童修改任何可能是子節點的深度。這裏發生的變化是在一個層面完成的,即跨度和h1標籤被消除。

顯示HTML按鈕顯示外部HTML文件的內容,而不是PAGE電泳代碼的源代碼轉換爲外部HTML文件的源代碼是這樣

<script> 
 
     function convertHtml() { 
 
      
 
    
 
      $body = $("#demo").text(); 
 
      $fakediv = $("<div></div>"); 
 
      $fakediv.html($body); 
 
      $fakediv.children().each(function(){ 
 
       
 
       $thisText = $(this).text(); 
 
       if($thisText) 
 
       $(this).text("@"+$thisText+"@") 
 
     
 
      }); 
 
      $("#demo").text($fakediv.prop("outerHTML")); //fill in the div with converted html string 
 
     
 
} 
 
      
 
     //Document is ready to execute the JS  
 
     $(document).ready(function() {  
 
      $("#convert").click(function(){ 
 
       // alert($("#demo").text()); 
 
       convertHtml(); 
 
      }); 
 
     }); 
 
     </script>

請幫助。

謝謝!

+0

分享你的代碼,我們將幫助您 – Zl3n

+0

你看着'的jQuery()。文本()'? ''(「*」)。each(function(){$(this).text(「@」+ $(this).text()+「@」)});'示例不會產生確切的效果嵌套元素。 –

+0

是的,我做到了,但那隻會修改DOM元素的內容,但我想修改的源代碼,我在我的帖子中提到的東西。 –

回答

-2

入住這撥弄它填補你的需求

$("#target").click(function() { 
 
    $('h1').html("HEllo"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<input type="button" value="ClickMe" id="target" /> 
 
<h1>This is need to change</h1>

+0

嗨,這個答案對你好嗎 –

+0

沒有,因爲我沒有提到我不需要預期的HTML頁面輸出,而不是我想修改源代碼,並且單擊按鈕時應顯示修改的源代碼。 –

-1

在這裏你去,按鈕上的點擊轉換的HTML將在文本框中,JS的評論,讓我知道如果你需要幫幫我。

$("#convert").click(function(){ /// on click of Convert button 
 
    $body = $("body").prop("outerHTML"); //Get a string of body content 
 
    $fakediv = $("<div></div>"); //Make a fake div to put that string inside it 
 
    $fakediv.html($body); // copy body to our fake div 
 
    $fakediv.children().not("#convert,#output").each(function(){ // for each child of our copied version 
 
    $thisText = $(this).text(); //get whatever text they have inside 
 
    if($thisText) 
 
    $(this).text("@"+$thisText+"@") // and replace it 
 
    }); 
 
    $("#output").text($fakediv.prop("outerHTML")); //fill in the text are with converted html string 
 
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<html> 
 
    <head> 
 
    </head> 
 
    <body> 
 
     <h1>Hello</h1> 
 
     <div id="something">Hello Folks!</div> 
 
     <span>Lovely lady</span> 
 
     <button id="convert">Convert</button> 
 
     <textarea id="output"></textarea> 
 
    </body> 
 

 
</html>