【问题标题】:how to add text and values to array如何将文本和值添加到数组
【发布时间】:2022-12-05 23:19:04
【问题描述】:

我需要搜索页面上的所有元素并添加到数组

现在主要的问题是找一段有.return class 的,如果里面有东西就写。

.return 段落可以为空且乱序,例如代码

code here

at the end it should look like something like this:
{phrase: 'hi'},
{phrase: 'who are you',return: 'member'},
{phrase: 'im from stackoverflow'},
{phrase: 'okay,what about your question?', return: 'about array'},

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    在浏览器环境中,您可以使用 querySelectorAll 方法:

    const paragraphsWithClassReturn = document.querySelectorAll('p.return');
    

    请参阅 MDN 上的querySelectorAll

    在此之后,您可以将结果转换为数组并使用可用的数组方法循环遍历它:

    Array.from(paragraphsWithClassReturn).forEach(paragraph => {
        // your code doing something with every found paragraph
    })
    

    在 jQuery 中,您选择具有返回类的元素使用

    const $paragraphsWithClassReturn = $('p.return')
    

    ...然后使用 .each 方法循环遍历它们:

    $paragraphsWithClassReturn.each($paragraph => {
        // your code doing something with every found paragraph
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      相关资源
      最近更新 更多