2017-11-14 4 views
-1

私はコンテンツとボタンを備えたhtmlページを持っています。 getDataボタンをクリックすると、各HTMLタグ情報を変数に格納する必要があるjavascript関数が呼び出されます。javascriptコードは、htmlタグ情報を取得し、jsコードの変数に格納します

デモ:https://plnkr.co/edit/wuIsu1qhcrYeoxtkrGxC?p=preview

JSコード:

function getData(){ 
     var $divs = $('.div1')  
     alert($divs); //[object Object] is printed 
     //var p_tags; 
     //var ul_tags; 
    } 

htmlコード:ケースあなたにタグ情報に

function getData(){ 
    var $divs = $('.div1').text(); 

    var p_tags = $('.div1 p').text(); 
    var ul_tags = $('.div1 ul').text(); 
} 

を取得する

<div> 
     <button onClick="getData()">GetData</button> 

    <div class="div1"> 
<p>The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly) </p> 

<p><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">This article is about the Internet encyclopedia. For Wikipedia's home page, see&nbsp;</span><a href="https://en.wikipedia.org/wiki/Main_Page" title="Main Page" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's Main Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For Wikipedia's visitor introduction, see&nbsp;</span><a href="https://en.wikipedia.org/wiki/Wikipedia:About" title="Wikipedia:About" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's About Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For other uses, see&nbsp;</span><a href="https://en.wikipedia.org/wiki/Wikipedia_(disambiguation)" class="mw-disambig" title="Wikipedia (disambiguation)" style="text-decoration-line: underline; color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia&nbsp;</a></p> 
<ul><li>one</li><li>two</li></ul> 
    </div></div> 

答えて

-2

使用テキスト()メソッドワその後、html()メソッドを使います。

4

alertで出力しようとするものは、jQueryオブジェクトです。ブラウザalertはオブジェクトの詳細を表示できません - 代わりに[object Object]が表示されます。

しかし、console.log($divs)を試してみると、さまざまなメソッドを実行してDOMを操作できるjQueryオブジェクトの詳細がわかります。

console.log($divs.html()) 
1

はい、それは、[オブジェクトのオブジェクト]を印刷しますが、それは少しはExpando-togglyボタンがあります。

enter image description here

たとえば、あなたは次のように選択した<div> Sの内部HTMLを取得することができます。その中の要素をループして表示します。

console.log($divs.html()) 
関連する問題