Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在jquery中按类名获取值_Jquery - Fatal编程技术网

在jquery中按类名获取值

在jquery中按类名获取值,jquery,Jquery,我想在jquery中按类名获取文本。我已经创建了一个函数来按类名获取元素的文本,但是通过这个函数,我得到了使用同一个类的三个元素的所有文本。我想获取数组中的文本,如x[0]或x[1]等等。请帮帮我 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script&

我想在jquery中按类名获取文本。我已经创建了一个函数来按类名获取元素的文本,但是通过这个函数,我得到了使用同一个类的三个元素的所有文本。我想获取数组中的文本,如x[0]或x[1]等等。请帮帮我

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $("#hide").click(function(){
          myfunction();

        });

        function myfunction(index) {
          var x = $(".check").text();

          $("#demo").text(x);}
      });
    </script>
  </head>
  <body>
    <div id="main">
      <p class="check">If you click on the "Hide"</p>
      <p class="check">button, I will disappear.</p>
      <p class="check">If you click on the "Hide" button</p>
    </div>
    <p id="demo">"Hide" button</p>
    <button id="hide">Hide</button>
    <button id="show">Show</button>

  </body>
</html>

您可以创建一个数组,并通过使用.each迭代每个元素来推送每个元素的文本 在任何需要的地方使用该阵列

$document.readyfunction{ $hide.clickfunction{ 我的功能; }; 函数myfunctionindex{ var数组=[]; var x=$.check.eachfunction{array.push$this.text}; console.logarray; $demo.textarray;} };

如果单击隐藏按钮

按钮,我将消失

如果单击隐藏按钮

隐藏按钮

隐藏
Show您可以使用每个jquery函数,并将每个段落保存在一个数组中。运行代码以查看结果。希望这个答案是你想要的:

$document.readyfunction{ $hide.clickfunction{ 我的功能; }; 函数myfunctionindex{ var x=[]; $.check.eachfunction{ x、 推送$this.text; }; $demo1.textx[0]; $demo2.textx[1]; $demo3.textx[2]; } }; 主要{ 边框底部:1px实心ccc; }

如果单击隐藏按钮

按钮,我将消失

如果单击隐藏按钮

第一次检查

第二次检查

第三次检查

隐藏
你可以用这种方法解决这个问题

 //Declare an Array
    var data=[];
   /**
     * Extract data from array element
     */
    var mydata = $(".check").each(function()
    {
    data.push(
    $(this).text())
    });

   //You can access your first p tag element 
    console.log(data[0]);

这回答了你的问题吗?