繁体   English   中英

javascript代码以获取html标签信息并将其存储在js代码中的变量中

[英]javascript code to get the html tag information and store in a variable in js code

我有一个带有内容和按钮的html页面。 当单击getData按钮时,将调用javascript函数,其中我必须将每个html标签信息存储到变量中。

演示: 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代码:

 <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>

您尝试通过alert输出的是jQuery对象。 浏览器alert无法显示对象的详细信息,而是打印[object Object]

但是,如果尝试使用console.log($divs) ,则可以看到jQuery对象的详细信息,可以在其上执行各种方法来操作DOM。

在此处输入图片说明

例如,您可以像这样获取所选<div>的内部HTML:

console.log($divs.html())

是的,它会打印[object Object],但它有一个小小的toggle切换按钮。因此,循环遍历其中的元素并显示它。

console.log($divs.html())

使用text()方法获取标签信息

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

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

如果您想要完整的HTM1,请使用html()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM