简体   繁体   English

将多个值推入Javascript中的数组不起作用

[英]Push multiple values into an array in Javascript not working

I'm trying to push multiple values into an array based on the elements ID. 我正在尝试根据元素ID将多个值推入数组。

I expect the outcome to be 3 and 4 but instead I get 1 2 3 4 . 我希望结果是34但我得到1 2 3 4 Why is that the case in the following example? 在以下示例中为什么会这样?

 var myArray = []; $( '#bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div id="bla">3</div> <div id="bla">4</div> </div> 

You are seeing the content of the your HTML, and not the console.log . 您正在看到HTML的内容,而不是console.log

This is what you need to fix: 这是您需要解决的问题:

  1. Include jQuery 包括jQuery
  2. Use class instead of id - there can be only one id in a document, so you'll get only one result 使用类而不是ID-文档中只能有一个ID,因此您只会得到一个结果
  3. Look at the console 看控制台

 var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

First id has to be unique replace id with class and use your snippet 第一个ID必须是唯一的,用class替换ID并使用您的代码段

 var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

First of all, you can't have two HTML elements with same id attribute. 首先,您不能有两个具有相同id属性的HTML元素。 It is unique indeficator, it should be only one on page. 它是唯一的缩略词,应该只有一页。

And second, if you are using your js script from external (not inluded between <scritp></script> ) you should use ( document.ready or in jQuery $(docuemnt).ready(function(){}) [in my case it is short way to do this]), because you don't want to read HTML values before your is not loaded. 其次,如果您从外部使用js脚本(在<scritp></script>之间没有使用),则应该使用( document.ready或jQuery $(docuemnt).ready(function(){}) [在我的情况,这是执行此操作的简短方法]),因为您不想在未加载HTML值之前就读取它。

 (function () { var myArray = []; $( '.bla' ).each( function() { myArray.push( { test: $( this ).text(), }); }); console.log( myArray ); }()); 
 <div> <div>1</div> <div>2</div> <div class="bla">3</div> <div class="bla">4</div> </div> 

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

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