首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的javascript:数组和表单信息收集#2

简单的javascript:数组和表单信息收集#2
EN

Stack Overflow用户
提问于 2016-02-13 08:55:59
回答 1查看 102关注 0票数 2

我一点也不了解javascript,我只是喜欢给自己列个列表。我目前正在尝试创建一个html页面,我可以跟踪我最喜欢的游戏中的人物,但我遇到了一些我不知道如何解决的问题。

代码语言:javascript
复制
<form name="inputNightlife" id="inputNightlife">
<h2>Nightlife</h2>
<label for="traits"><b>Traits:</b></label><br>
<select multiple="true" name="traits" id="traits">
        <option value="Cologne">Cologne</option>
        <option value="Stink">Stink</option>
        <option value="Fatness">Fatness</option>
        <option value="Fitness">Fitness</option>
    </select>
<label for="turnOns"><b>Turn Ons:</b></label><br>
<select multiple="true" name="turnOns" id="turnOns">
        <option value="Blonde Hair">Blonde Hair</option>
        <option value="Red Hair">Red Hair</option>
        <option value="Brown Hair">Brown Hair</option>
        <option value="Black Hair">Black Hair</option>
    </select>
    <p>Select all that apply.</p>
<nav id="box8" class="hide"><table id="menu3"><tr><td rowspan="2" id="soft">
<textarea name="source8" onclick="this.focus();this.select()" cols="40" rows="3" id="result">
</textarea></td><td>
<input type="button" value="Get Code!" onclick="javascript:generateNightlife();"></td>
<td rowspan="2" id="softA">
<img src="./forSCV/icons/nightlife.png" alt="Nightlife" title="Nightlife" id="arrow" onclick="toggle('box8');">
</td></tr><tr><td>
<input type="button" value="Test Code" onclick="javascript:displayNightlife(this.form);">
</td></tr></table></nav></form>

当我单击该按钮时,document.results.endresults.value出现在文本区域中。然后我可以复制结果,并将它们保存为html。这是一个页面生成器(这是我能想到的最好的)。

我不确定如何让特征和turnOns自动创建一个所选选项的数组(带空格),然后在document.result.endresult.value中打印出来。我确实找到了几种从表单创建数组的不同方法,但没有找到如何将其放入document.result.endresult.value中的方法。

单向Google。和另一种方式Google

正在添加...

好的,我修改了我的html以包含名字和id,我发现了一个更好的页面生成器,所以我试着让它工作。现在我已经尝试过了。

代码语言:javascript
复制
function byId(idStr){return document.getElementById(idStr);}

function getFormValues() {
var traitsSelectElem = byId('traits');
var turnOnsSelectElem = byId('turnOns');
var chosenTraits = getSelectedOptions(traitsSelectElem);
var chosenTurnOns = getSelectedOptions(turnOnsSelectElem);
var i, n, outputStr;
n = chosenTraits.length;
outputStr = '';
for (i = 0; i < n; i ++)
{
    if (outputStr != ".")
        outputStr += ", ";
    outputStr += chosenTraits[i].value;
}
byId('traitsOutput').innerText = outputStr;

n = chosenTurnOns.length;
outputStr = '';
for (i = 0; i < n; i++)
{
    if (outputStr != '.')
        outputStr += ', ';
    outputStr += chosenTurnOns[i].value;
}
byId('turnOnsOutput').innerText = outputStr;
}
function getSelectedOptions(selectElem) {
var i, nOptions = selectElem.options.length;
var result = [];
for (i = 0; i < nOptions; i++)
{
    if (selectElem.options[i].selected)
    {
        result.push(
                        {
                            value: selectElem.option[i].value
                        }
                    );
    }
}
return result;
}

function generateNightlife() {

//nightlife
var traits = getFormValues();
var turnOns = getFormValues();
turnOff = document.inputNightlife.turnOff.value;
perfumeDuration = document.inputNightlife.perfumeDuration.value;
lovePotion = document.inputNightlife.lovePotion.value;

outputNightlife = "<a name='nightlife'></a>\n<div id='easy'>\n<h2>Nightlife</h2>\n
<table class='ntlf'><tr><th>Traits:</th><td class='white'>"+traits+"
</td></tr><tr><th>Turn Ons:</th><td class='white'>"+turnOnsOutput+"</td></tr><tr><th>
Turn Offs:</th><td class='white'>"+turnOff+"</td></tr></table>\n<p class='up2'>Perfume 
Duration: <span class='colorme'>"+perfumeDuration+"</span></p>\n<p>Love Potion Duration: 
<span class='colorme'>"+lovePotion+"</span></p>\n</div>\n"

document.inputNightlife.source8.value = outputNightlife;

return outputNightlife;
}

当我用chrome测试它时,它告诉我它不能将.innerText的属性设置为null,我想这是因为我不想让它变成一个div。我希望将值返回给函数generateNightlife,以便可以将其添加到outputNightlife中。我不知道该怎么做,我需要一些帮助。

EN

回答 1

Stack Overflow用户

发布于 2016-02-13 11:20:14

这里有一个完整的例子,它将从一个select元素中提取多个选择,然后用它们构造一个数组,最后将它们打印到屏幕上。

你链接的两个教程中的任何一个都是可以的--总是很难知道什么是显而易见的,什么是需要解释的,什么将依赖于可能/可能没有被覆盖的背景信息。

我在这里使用了一些不同的技巧,还有许多我选择避免使用的更复杂的技巧。我希望这些评论能让操作变得清晰,尽管如果需要的话,我很乐意补充说明。:)

下面是一个可运行的代码片段:

代码语言:javascript
复制
function byId(idStr){return document.getElementById(idStr);}

function getFormValues()
{
	// 1. get a reference to each of the select elemenets we wish to process
	var mainMealSelectElem = byId('mainSelect');
	var dessertSelectElem = byId('dessertSelect');

	// 2. get an array of all of the selected options in each of our select elements
	var chosenMains = getSelectedOptions(mainMealSelectElem);
	var chosenSweets = getSelectedOptions(dessertSelectElem);
	
	var i, n, outputStr;
	n = chosenMains.length;
	outputStr = '';
	for (i=0; i<n; i++)
	{
		// only add a comma before an element if at least one element already exists
		// this is how we do it when writing a list manually.
		if (outputStr != '')
			outputStr += ", ";
			
		// grab the two values from the array we constructed using the getSelectedOptions function.
		// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
		// whatever we named them in the below function is what we need to use to access them here.
		outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
	}
	// set the text content of the target span with the array of chosen stuff.
	byId('mainsOutput').innerText = outputStr;

	
	n = chosenSweets.length;
	outputStr = '';
	for (i=0; i<n; i++)
	{
		if (outputStr != '')
			outputStr += ", ";
		outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
	}
	byId('dessertsOutput').innerText = outputStr;
}

// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
	// aloop counter and the total number of iterations required
	var i, nOptions = selectElem.options.length;
	
	// the empty result array
	var result = [];
	
	// loop through all the options this select element has
	for (i=0; i<nOptions; i++)
	{
		// if the current option is selected, we'll need to extract it's info and add it to the output array
		if (selectElem.options[i].selected)
		{
			result.push( 
							{
								value: selectElem.options[i].value, 
								textLabel: selectElem.options[i].label
							}
						);
		}
	}
	return result;
}
代码语言:javascript
复制
div
{
	display: inline-block;
}
.centered
{
	text-align: center;
}
代码语言:javascript
复制
<div class='centered'>
		<form>
			<h2>Select the ones you like</h2>
			<select id='mainSelect' multiple>
				<option value='spag'>Spaghetti</option>
				<option value='satay'>Peanut satay</option>
				<option value='schnitz'>Chicken Schnitzel</option>
			</select>
			<select id='dessertSelect' multiple>
				<option value='1'>Ice-cream</option>
				<option value='2'>Fruit salad</option>
				<option value='3'>Custard</option>
			</select>
		</form>
		<br>
		<button onclick='getFormValues()'>Get chosen values</button>
		<hr>
	</div>
	<br>
	<div>
		Selected main-meals: <span id='mainsOutput'></span><br>
		Selected desserts: <span id='dessertsOutput'></span><br>
	</div>

下面是完整的(复制/粘贴)源代码:

代码语言:javascript
复制
<!doctype html>
<html>
<head>
<script>
function byId(idStr){return document.getElementById(idStr);}

function getFormValues()
{
    // 1. get a reference to each of the select elemenets we wish to process
    var mainMealSelectElem = byId('mainSelect');
    var dessertSelectElem = byId('dessertSelect');

    // 2. get an array of all of the selected options in each of our select elements
    var chosenMains = getSelectedOptions(mainMealSelectElem);
    var chosenSweets = getSelectedOptions(dessertSelectElem);

    var i, n, outputStr;
    n = chosenMains.length;
    outputStr = '';
    for (i=0; i<n; i++)
    {
        // only add a comma before an element if at least one element already exists
        // this is how we do it when writing a list manually.
        if (outputStr != '')
            outputStr += ", ";

        // grab the two values from the array we constructed using the getSelectedOptions function.
        // we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
        // whatever we named them in the below function is what we need to use to access them here.
        outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
    }
    // set the text content of the target span with the array of chosen stuff.
    byId('mainsOutput').innerText = outputStr;


    n = chosenSweets.length;
    outputStr = '';
    for (i=0; i<n; i++)
    {
        if (outputStr != '')
            outputStr += ", ";
        outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
    }
    byId('dessertsOutput').innerText = outputStr;
}

// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
    // aloop counter and the total number of iterations required
    var i, nOptions = selectElem.options.length;

    // the empty result array
    var result = [];

    // loop through all the options this select element has
    for (i=0; i<nOptions; i++)
    {
        // if the current option is selected, we'll need to extract it's info and add it to the output array
        if (selectElem.options[i].selected)
        {
            result.push( 
                            {
                                value: selectElem.options[i].value, 
                                textLabel: selectElem.options[i].label
                            }
                        );
        }
    }
    return result;
}
</script>
<style>
div
{
    display: inline-block;
}
.centered
{
    text-align: center;
}
</style>
</head>
<body>
    <div class='centered'>
        <form>
            <h2>Select the ones you like</h2>
            <select id='mainSelect' multiple>
                <option value='spag'>Spaghetti</option>
                <option value='satay'>Peanut satay</option>
                <option value='schnitz'>Chicken Schnitzel</option>
            </select>
            <select id='dessertSelect' multiple>
                <option value='1'>Ice-cream</option>
                <option value='2'>Fruit salad</option>
                <option value='3'>Custard</option>
            </select>
        </form>
        <br>
        <button onclick='getFormValues()'>Get chosen values</button>
        <hr>
    </div>
    <br>
    <div>
        Selected main-meals: <span id='mainsOutput'></span><br>
        Selected desserts: <span id='dessertsOutput'></span><br>
    </div>
</body>
</html>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35374747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档