根据元素的数量附加到数组

时间:2017-11-22 15:57:01

标签: javascript jquery html arrays

这是我目前的代码:



<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
	 console.log("submitted");
	 $(".container").children("div").each(function() {
	   var title = $(this).find(".line-title").val();
	   var firstNum = $(this).find(".first-number-el input").val();
	   var secondNum = $(this).find(".second-number-el input").val();
	   console.log('your array is: [{"posx":'+ firstNum + ',"posy":' + secondNum+',"text":"'+ title +'"}]');
	 })

	}
	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>
&#13;
&#13;
&#13;

当只有一行时,代码正常工作,因为数组是以我想要的格式输出的。但是,当有多行时,它会使用不同的变量再次输出相同的行。

我希望它看起来像这样:

例如,如果这是输入 enter image description here

我希望输出看起来像这样:

submitted your array is: [{"posx":1,"posy":-1,"text":"test1"},{"posx":-0.1,"posy":0.05,"text":"test2"}]

另一个例子,如果有3行像这样

enter image description here

我希望输出看起来像这样:

submitted your array is: [{"posx":1,"posy":-1,"text":"test1"},{"posx":-0.1,"posy":0.05,"text":"test2"},{"posx":-0.3,"posy":0.25,"text":"test3"}]

如何根据行数使输出看起来像这样?

感谢所有帮助,谢谢。

4 个答案:

答案 0 :(得分:2)

在打印之前,您需要将输出保存到数组中。见下文。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
console.log("submitted");
var output = [];
$(".container").children("div").each(function () {
	var title = $(this).find(".line-title").val();
	var firstNum = $(this).find(".first-number-el input").val();
	var secondNum = $(this).find(".second-number-el input").val();
	output.push({
		"posx": firstNum,
		"posy": secondNum,
		"text": title
	});
});
console.log('your array is: ' + JSON.stringify(output));
}

	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

与@zatopeks类似,但我有点迟了......

<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
	 console.log("submitted");
     var all_items = []
	 $(".container").children("div").each(function() {
       var tmp_item = {
          "text": $(this).find(".line-title").val(),
          "posx": parseFloat($(this).find(".first-number-el input").val()),
          "posy": parseFloat($(this).find(".second-number-el input").val())
       }
       all_items.push(tmp_item)
	 })
     console.log('your array is: ' + JSON.stringify(all_items));

	}
	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>

答案 2 :(得分:1)

使用map()为每行创建一个对象数组。

向行中添加一些类以使其易于隔离,然后映射每一行

const data = $('.input-row').map(function() {
  const $row = $(this)
  return {
    posx: $row.find('.pos-x').val(),
    posy: $row.find('.pos-y').val(),
    text: $row.find('.line-title').val()
  };
}).get()

console.log(data)
.as-console-wrapper {	max-height: 100%!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-row">
  <input class="line-title" value="Text 1">
  <input class="line-number pos-x" value="1">
  <input class="line-number pos-y" value="2">
</div>
<div class="input-row">
  <input class="line-title" value="Text 2">
  <input class="line-number pos-x" value="3">
  <input class="line-number pos-y" value="4">
</div>

答案 3 :(得分:0)

仔细查看提交的()中发生的事情。在每个循环上打印该行。你想要的是提前打印手续,然后在循环期间只打印{}对象。

这样的事情,可能是:

<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
	 console.log("submitted");
     let buffer = 'your array is: [';
	 $(".container").children("div").each(function() {
	   var title = $(this).find(".line-title").val();
	   var firstNum = $(this).find(".first-number-el input").val();
	   var secondNum = $(this).find(".second-number-el input").val();
	   buffer += '{"posx":'+ firstNum + ',"posy":' + secondNum+',"text":"'+ title +'"}';
     buffer += ']';
     console.log(buffer);
	 })

	}
	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>