2009-09-16 2 views
5

У меня есть следующий HTMLКак получить содержимое div, которое содержит блоки сценариев JavaScript?

<div id="example"> 
    ...some text... 
    <script type="text/javascript"> 
    ... some javascript... 
    </script> 
</div> 

Как получить содержание #example, но и с JavaScript?

$("#example").html(), 
$("#example").text(),  
$("#example").val()  

все не работает.

+4

ваш Javascript не принадлежит там – Natrium

+1

$ .html() должно было сработать. интересно, почему. – mauris

ответ

5

Working Demo

Вы можете использовать

html(): Получить содержимое HTML (innerHTML) первого совпавшего элемента.

var contents = $("#example").html(); 
+1

когда я использую $ ("# example"). Html(); Я получаю только содержимое div, но без этого javascript он игнорирует все javascript –

11

Метод html() должен работать на вас. Вы уверены, что используете код после завершения DOM?

$(document).ready(function(){ 
    alert($("#example").html()); 
}); 
+0

.html() будет лишать все теги

1
var txt = document.getElementById("example").innerHTML; 

Это загрузит вам InnerText от дел. Напишите эту строку в конце вашего тега тега. Или называют его в метод, который будет вызываться после того, как OnLoad тела

0
<!--This code will work --> 
<html> 
<head>  
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" lang='text/javascript' />--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 

//alert($('#example p').html()); 
alert($('#example').text()); 

alert($('#example #1').text()); 
alert($('#example #2').text()); 
alert($('#example #3').text()); 
alert($('#example #4').text()); 
//alert($("#example p").get().innerHTML); 
//alert('hey'); 


}); 
</script> 
</head> 
<body> 
<div id="example"> 
    <p>...some text...</p> 
    <div id="1"> 
    Here's 1 
    </div> 
    <div id="2"> 
    Here's 2 
    </div> 
    <div id="3"> 
    Here's 3 
    </div> 
    <div id="4"> 
    Here's 4 
    </div> 

</div> 

</body> 
</html> 
+0

Возможно, вы захотите добавить описание своего решения, чтобы объяснить, что вы делаете и почему. – Sgoettschkes

0
menuItem.firstChild.innerHTML 

Возможно, это помогает.

0

Это работает для меня:. $ («# пример») содержание()

0

В моем случае я получаю фрагмент кода HTML обратно из веб-службы (как свойство в объект возвращается в виде JSON) , Я хочу отображать его без форматирования, а также без блоков javascript. .html() действительно возвращает блоки javascript для меня, так что это не сработает.

То, что я закончил с было:

// Build up the message a bit artificially for this demo. 
// is actually response from ajax call 
var message = '<scri'; 
message += 'pt type="text/javascript">var foo = "bar";</scr' 
message += 'ipt><h2>A heading</h2><div>This is a message</div>'; 

var message_html = jQuery('<div/>') // create a container 
    .html(message) // set the contents from the message 
    .find('script') // find script blocks 
    .remove() // and remove them 
    .end(); // back to the original collection but without script blocks 
// Now get just the text from there 
alert(message_html.text()); 

Working fiddle

Смежные вопросы