且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将外部对象添加到现有数组

更新时间:2023-02-18 14:22:28

p>表单提交有一个问题:




  • 你有 onclick =addExtUser() 在提交按钮上,但是尽管您在该函数中返回 false ,但此返回值将被忽略。它应该是 onclick =return addExtUser()


  • 表单的提交事件有一个监听器,也会调用 addExtUser 。但是,表单的 id 是拼写错误的:它应该是 $(#extUserForm)。提交而不是 $( #extArticleForm)。提交


  • 但是您只需要调用 addExtUser 的一种方法,因此请删除以上其中之一。我会建议第二种方式(纠正拼写)。




你可能希望隐藏表单首先,将 style =display:none添加到HTML。



有一些重复的代码,因为 addExtUser 具有与 refreshDisplay 相同的许多代码:在将数据添加到 savedData 之后,您应该调用 refreshDisplay EM>。



请注意, savedData.push 地图上不是有效的方法,但是我建议使用一个简单的数组(参见你的另一个交换记录的问题)。



定义对象的方式与JSON非常相似句法。这不行:

  extObj = {}; 
extObj [name] [title] =mr;

但这将:

  var extObj = {
name:{
title:mr,// No ladies? :-)
first:$(#name)。val(),
//姓氏?
},
dob:$(#dob)。val(),
图片:{
thumbnail:$(#myImg)val()
},
位置:{//也可能要求这个信息?
}
};

这是一个实现所有这一切的代码段:



function createTable(){$ .getJSON(https://api.randomuser.me/?results=5,function (数据){$('#datatable tr:has(td)')。remove(); data.results.forEach(function(record){var json = JSON.stringify(record); $('#datatable' .append($('< tr>')。append($('< td>')。append($('< input>')。attr('type','checkbox').addClass 'selectRow').val(json)),$('< td>')。append($('< a>')。attr('href',record.picture.thumbnail) .addClass('imgurl').attr('target','_blank').text(record.name.first)),$('< td>')。append(record.dob))) })})。fail(function(error){console.log(********** AJAX ERROR:+ error);}); } var savedData = []; //对象为数组,所以要有一个order.function saveData(){var errors = []; //添加选择映射$('input.selectRow:checked')。each(function(count){//获取存储为checkbox的值的JSON var obj = JSON.parse($(this).val ()); //看看这个URL是否已经被收集(这很容易使用Set)if(savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)){errors.push(obj .name.first);} else {//附加它savedData.push(obj);}}); refreshDisplay(); if(errors.length){alert('以下内容已经被选中:\\\
'+ errors.join('\\\
')); }} function refreshDisplay(){$('。container')。html(''); saveData.forEach(function(obj){//重置容器,并附加收集的数据(使用jQuery进行追加)$('。container')。append($('< div>')addClass('parent' .append($('< label>')。addClass('dataLabel').text('Name:'),obj.name.first +''+ obj.name.last,$('< br& '),// name& pic $('< img>')之间的换行符addClass('myLink')。attr('src',obj.picture.thumbnail),$('< br> '',$('< label>')。addClass('dataLabel')。text('Date of birth:'),obj.dob,$('< br>'),$('< label> ;')。addClass('dataLabel')。text('Address:'),$('< br>'),obj.location.street,$('< br>'),obj.location.city +''+ obj.location.postcode,$('< br>'),obj.location.state,$('< br>') $('< button>')。addClass('removeMe')。text('Delete'),$('< button>')addClass('top-btn' ),$('< button>')。addClass('down-btn')。text('Swap with down'))) })//清除复选框:$('。selectRow')。prop('checked',false); handleEvents();} function logSavedData(){//转换为JSON并记录到控制台。你会把它//发布到一些URL,或将其保存到localStorage。 console.log(JSON.stringify(savedData,null,2));} function getIndex(elem){return $(elem).parent('。parent')。index();} $(document)点击','.removeMe',function(){//从保存的Data savedData.splice(getIndex(this),1); //重新显示refreshDisplay();}); / *将所显示的文章结果列表* / $(document).on('click','.down-btn,function(){var index = getIndex(this); //在内存中交换saveData.splice(index,2,savedData [索引+ 1],savedData [index]); //并重新显示refreshDisplay();}); $(document).on('click',.top-btn,function(){var index = getIndex ); //在内存中交换saveData.splice(index-1,2,savedData [index],savedData [index-1]); //并重新显示refreshDisplay();}); / *禁用顶部&结果列表中第一个和最后一个文章的下拉按钮* / function handleEvents(){$(。top-btn,.down-btn)。prop(disabled,false).show(); $(。parent:first)。find(。top-btn)。prop(disabled,true).hide(); $(文件).ready(function(){$('#showExtForm -b()()()()()()()()() ;}); function addExtUser(){var extObj = {name:{title:mr,// No ladies? :-) first:$(#name)。val(),//姓氏? },dob:$(#dob)。val(),图片:{thumbnail:$(#myImg)。val()},location:{//也可能要求这个信息? }}; savedData.push(extObj); refreshDisplay(); //将显示一些未定义的东西(位置...)}

  table,th,td {border:1px solid #ddd;边界崩溃:崩溃padding:10px;}。parent {height:25%;宽度:90%;填充:1%;剩余左:1%;保证金:1%; border:1px solid black;}。parent:nth-​​child(odd){background:skyblue;}。parent:nth-​​child(even){background:green;} label {float:left; width:80px;} input {width:130px;}  

  < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< button onclick =createTable()&gt ;创建表< / button>< table id =datatable> < tr>< th>选择< thth>< th> DOB< / th>< th>< / th>< / tr>< / table>< button onclick =saveData > Save Selected< / button>< br />< div class =container>< / div>< button onclick =logSavedData()>获取保存的数据< / button>< ; button id =showExtForm-b​​tn>打开外部窗体< / button>< div id =extUserstyle =display:none> < form id =extUserForm> &LT; p为H. < label for =name> Name:< / label> < input type =textid =namerequired> &LT; / p为H. < br /> &LT; p为H. < label for =myImg> Image:< / label> < input type =urlid =myImgrequired> &LT; / p为H. < br /> &LT; p为H. < label for =dob> DOB:< / label> < input type =dateid =dobrequired> &LT; / p为H. < br /> &LT;按钮&GT;提交&LT; /按钮&GT; < / form>< / div>  


I've a table which gets updated based on JSON data. Each row in the table has a checkbox which holds the value of the corresponding JSON object, which is basically the information about any of the users. On selecting any of the rows, and saving to display the selected user profile, I'm also storing the selected JSON object in an array 'savedData'.

I also have an option of adding the user externally through a form which pops up on clicking 'Open External form' button. Now, I'm trying to create an object and store it in the same 'savedData' array on submitting that form. At the same time, the 'div.parent' should get generated & get appended to 'div.container' in the same format as it is for the the other users selected from the table.

Unfortunately, the 'div.parent' is not getting created, and the external object is not getting added.

Could you please help me fix this?

function createTable() {
			$.getJSON("https://api.randomuser.me/?results=5", function(data) {
				$('#datatable tr:has(td)').remove();
				data.results.forEach(function (record) {
					var json = JSON.stringify(record);
					$('#datatable').append(
						$('<tr>').append(
							$('<td>').append(
								$('<input>').attr('type', 'checkbox')
											.addClass('selectRow')
											.val(json)
							),
							$('<td>').append(
								$('<a>').attr('href', record.picture.thumbnail)
										.addClass('imgurl')
										.attr('target', '_blank')
										.text(record.name.first)
							),
							$('<td>').append(record.dob)
						)
					);
				})
			}).fail(function(error) {
				console.log("**********AJAX ERROR: " + error);
			});            
		}

		var savedData = new Map; // Keyed by image URL. Start with nothing.

		function saveData(){
			var errors = [];
			// Add selected to map
			$('input.selectRow:checked').each(function(count) {
				// Get the JSON that is stored as value for the checkbox
				var obj = JSON.parse($(this).val());
				// See if this URL was already collected (that's easy with Set)
				if (savedData.get(obj.picture.thumbnail)) {
					errors.push(obj.name.first);
				} else {
					// Append it to the Map:
					savedData.set(obj.picture.thumbnail, obj);
				}
			});
			refreshDisplay();
			if (errors.length) {
				alert('The following were already selected:\n' + errors.join('\n'));
			}
		}

		function refreshDisplay() {
			$('.container').html('');
			savedData.forEach(function (obj) {
				// Reset container, and append collected data (use jQuery for appending)
				$('.container').append(
					$('<div>').addClass('parent').append(
						$('<label>').addClass('dataLabel').text('Name: '),
						obj.name.first + ' ' + obj.name.last,
						$('<br>'), // line-break between name & pic
						$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
						$('<label>').addClass('dataLabel').text('Date of birth: '),
						obj.dob, $('<br>'),
						$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
						obj.location.street, $('<br>'),
						obj.location.city + ' ' + obj.location.postcode, $('<br>'),
						obj.location.state, $('<br>'),
						$('<button>').addClass('removeMe').text('Delete'),
						$('<button>').addClass('top-btn').text('Swap with top'),
						$('<button>').addClass('down-btn').text('Swap with down')
					)	
				);
				resetEvents();
			})
			// Clear checkboxes:
			$('.selectRow').prop('checked', false);
		}

		function logSavedData(){
			// Translate Map to array of values:
			var data = Array.from(savedData, function (pair) {
				return pair[1];
			});
			// Convert to JSON and log to console. You would instead post it
			// to some URL, or save it to localStorage.
			console.log(JSON.stringify(data, null, 2));
		}

		$(document).on('click', '.removeMe', function() {
			var key = $('.myLink', $(this).parent()).attr('src');
			// Delete this from the saved Data
			savedData.delete(key);
			// And redisplay
			refreshDisplay();
		});
		
			/* Swapping the displayed articles in the result list */
			function resetEvents() {

				$(".top-btn, .down-btn").unbind('click');

				handleEvents();
				
				$('.down-btn').click(function() {
					var toMove1 = $(this).parents('.parent');

					$(toMove1).insertAfter($(toMove1).next());

					handleEvents();
				});

				$('.top-btn').click(function() {
					var toMove1 = $(this).parents('.parent');
					
					$(toMove1).insertBefore($(toMove1).prev());
					handleEvents();
				});

			}
				
			/* Disable top & down buttons for the first and the last article respectively in the result list */
			function handleEvents() {
				$(".top-btn, .down-btn").prop("disabled", false).show();

				$(".parent:first").find(".top-btn").prop("disabled", true).hide();

				$(".parent:last").find(".down-btn").prop("disabled", true).hide();
			}
			
			$(document).ready(function(){
				$('#showExtForm-btn').click(function(){
					$('#extUser').toggle();
				});
				$("#extArticleForm").submit(function(){

                    addExtUser();
                    return false;
               });
			});
			
			function addExtUser() {
				var name= $("#name").val();
				var imgsrc = $("#myImg").val();
				var dob = $("#dob").val();
				
				var errors = [];
                extObj = {};
				extObj = {};
				extObj["name"]["title"] = "mr";
				extObj["name"]["first"] = name;
				extObj["dob"] = dob;
				extObj["picture"]["thumbnail"] = imgsrc;
				savedData.push(extObj);
				if (savedData.get(imgsrc)) {
						errors.push(title);
					} else {
				$('.container').append(
					$('<div>').addClass('parent').append(
						$('<label>').addClass('dataLabel').text('Name: '),
						+name+
						$('<br>'), // line-break between name & pic
						$('<img>').addClass('myLink').attr('src', imgsrc), $('<br>'),
						$('<label>').addClass('dataLabel').text('Date of birth: '),
						+dob+ $('<br>'),
						$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
						+address+ $('<br>'),
						$('<button>').addClass('removeMe').text('Delete'),
						$('<button>').addClass('top-btn').text('Swap with top'),
						$('<button>').addClass('down-btn').text('Swap with down')
					)	
				);
				resetEvents();
				
			}

table, th, td {
			border: 1px solid #ddd;
			border-collapse: collapse;
			padding: 10px;
		}

		.parent {
			height: 25%;
			width: 90%;
			padding: 1%;
			margin-left: 1%;
			margin-top: 1%;
			border: 1px solid black;

		}

		.parent:nth-child(odd){
			background: skyblue;
		}

		.parent:nth-child(even){
			background: green;
		}
		
		label {
			float: left;
			width: 80px;
		}
		input, textarea {
			width: 130px;
		}
		
		#extUser {
			border: 1px solid lightgrey;
			border-radius: 5px;
			display: none;
			padding: 10px;
			background-color: skyblue;
		}
		
		#extUserForm {
			margin: 3px;
			padding: 5px;
		}

<button onclick="createTable()">Create Table</button>
		<table id="datatable">
			<tr><th>Select</th><th>Name</th><th>DOB</th></tr>
		</table>
		<button onclick="saveData()">Save Selected</button>
		<br />
		<div class="container"></div>
		<button onclick="logSavedData()">Get Saved Data</button>
		<button id="showExtForm-btn">Open External Form</button>
		
		<div id="extUser">
			<form id="extUserForm">
				<p>
					<label for="name">Name:</label>
					<input type="text" id="name" required>
				</p>
				<br />
				<p>
					<label for="myImg">Image:</label>
					<input type="url" id="myImg" required>
				</p>
				<br />
				<p>
					<label for="dob">DOB:</label>
					<input type="date" id="dob" required>
				</p>
				<br />
				<button onclick="addExtUser()">Submit</button>
			</form>
		</div>

There is an issue with the form submission:

  • you have onclick="addExtUser()" on the submit button, but although you return false in that function, this return value is ignored. It should have been onclick="return addExtUser()".

  • There is a listener to the form's submit event that also calls addExtUser. However, the id of the form is misspelled: it should be $("#extUserForm").submit instead of $("#extArticleForm").submit.

  • But you need only one way of calling addExtUser, so remove one of the above. I would suggest the second way (with the correction of the spelling).

You probably want the form to be hidden at first, so add style="display:none" to the HTML.

There is some duplication of code, as addExtUser has a lot of code in common with refreshDisplay: you should call refreshDisplay after having added the data to savedData.

Note that savedData.push is not a valid method on a Map, but I would suggest to use a plain array (see your other question on swapping records).

The way to define your object is quite similar to JSON syntax. This will not work:

extObj = {};
extObj["name"]["title"] = "mr";

But this will:

var extObj = {
    name: {
        title: "mr", // No ladies? :-)
        first: $("#name").val(),
        // Last name ?
    },
    dob: $("#dob").val(),
    picture: {
        thumbnail: $("#myImg").val()
    },
    location: { // maybe also ask for this info?
    }
};

Here is a snippet that implements all this:

function createTable() {
    $.getJSON("https://api.randomuser.me/?results=5", function(data) {
        $('#datatable tr:has(td)').remove();
        data.results.forEach(function (record) {
            var json = JSON.stringify(record);
            $('#datatable').append(
                $('<tr>').append(
                    $('<td>').append(
                        $('<input>').attr('type', 'checkbox')
                                    .addClass('selectRow')
                                    .val(json)
                    ),
                    $('<td>').append(
                        $('<a>').attr('href', record.picture.thumbnail)
                                .addClass('imgurl')
                                .attr('target', '_blank')
                                .text(record.name.first)
                    ),
                    $('<td>').append(record.dob)
                )
            );
        })
    }).fail(function(error) {
        console.log("**********AJAX ERROR: " + error);
    });            
}

var savedData = []; // The objects as array, so to have an order.

function saveData(){
    var errors = [];
    // Add selected to map
    $('input.selectRow:checked').each(function(count) {
        // Get the JSON that is stored as value for the checkbox
        var obj = JSON.parse($(this).val());
        // See if this URL was already collected (that's easy with Set)
        if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
            errors.push(obj.name.first);
        } else {
            // Append it
            savedData.push(obj);
        }
    });
    refreshDisplay();
    if (errors.length) {
        alert('The following were already selected:\n' + errors.join('\n'));
    }
}

function refreshDisplay() {
    $('.container').html('');
    savedData.forEach(function (obj) {
        // Reset container, and append collected data (use jQuery for appending)
        $('.container').append(
            $('<div>').addClass('parent').append(
                $('<label>').addClass('dataLabel').text('Name: '),
                obj.name.first + ' ' + obj.name.last,
                $('<br>'), // line-break between name & pic
                $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
                $('<label>').addClass('dataLabel').text('Date of birth: '),
                obj.dob, $('<br>'),
                $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
                obj.location.street, $('<br>'),
                obj.location.city + ' ' + obj.location.postcode, $('<br>'),
                obj.location.state, $('<br>'),
                $('<button>').addClass('removeMe').text('Delete'),
                $('<button>').addClass('top-btn').text('Swap with top'),
                $('<button>').addClass('down-btn').text('Swap with down')
            )	
        );
    })
    // Clear checkboxes:
    $('.selectRow').prop('checked', false);
    handleEvents();
}

function logSavedData(){
    // Convert to JSON and log to console. You would instead post it
    // to some URL, or save it to localStorage.
    console.log(JSON.stringify(savedData, null, 2));
}

function getIndex(elem) {
    return $(elem).parent('.parent').index();
}

$(document).on('click', '.removeMe', function() {
    // Delete this from the saved Data
    savedData.splice(getIndex(this), 1);
    // And redisplay
    refreshDisplay();
});

/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index, 2, savedData[index+1], savedData[index]);
    // And redisplay
    refreshDisplay();
});

$(document).on('click', ".top-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
    // And redisplay
    refreshDisplay();
});
    
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}

$(document).ready(function(){
    $('#showExtForm-btn').click(function(){
        $('#extUser').toggle();
    });
    $("#extUserForm").submit(function(e){
        addExtUser();
        return false;
   });
});

function addExtUser() {
    var extObj = {
        name: {
            title: "mr", // No ladies? :-)
            first: $("#name").val(),
            // Last name ?
        },
        dob: $("#dob").val(),
        picture: {
            thumbnail: $("#myImg").val()
        },
        location: { // maybe also ask for this info?
        }
    };
    savedData.push(extObj);
    refreshDisplay(); // Will show some undefined stuff (location...)
}

table, th, td {
    border: 1px solid #ddd;
    border-collapse: collapse;
    padding: 10px;
}

.parent {
    height: 25%;
    width: 90%;
    padding: 1%;
    margin-left: 1%;
    margin-top: 1%;
    border: 1px solid black;

}

.parent:nth-child(odd){
    background: skyblue;
}

.parent:nth-child(even){
    background: green;
}

label {
    float: left;
    width: 80px;
}
input {
    width: 130px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createTable()">Create Table</button>
<table id="datatable">
    <tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>
<button onclick="saveData()">Save Selected</button>
<br />
<div class="container"></div>
<button onclick="logSavedData()">Get Saved Data</button>
<button id="showExtForm-btn">Open External Form</button>

<div id="extUser" style="display:none">
    <form id="extUserForm">
        <p>
            <label for="name">Name:</label>
            <input type="text" id="name" required>
        </p>
        <br />
        <p>
            <label for="myImg">Image:</label>
            <input type="url" id="myImg" required>
        </p>
        <br />
        <p>
            <label for="dob">DOB:</label>
            <input type="date" id="dob" required>
        </p>
        <br />
        <button>Submit</button>
    </form>
</div>