4

谁能告诉我为什么这个jsFiddle不起作用?

这个想法很简单,只是假设将选定的文本输入到文本框中。

HTML:

<input type="text" id="teste" maxlength="50">
<select>
    <option onClick="nelson">nelson</option>
</select>

JavaScript:

function nelson(){
    document.getElementById('teste').value =+ "nelson"; 
}

提前致谢

4

6 回答 6

8

演示:jsFiddle

HTML:

<input type="text" id="teste" maxlength="50" />
<select onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

JS:

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

解释:

<option onClick="nelson">nelson</option>
  • 改了三个原因:

    1. onclick优先onClick于一致性
    2. nelson需要更改为nelson()实际调用该函数。
    3. 由于我们正在处理一个selecthtml 元素,因此最好 onchange在根上使用该事件。

document.getElementById('teste').value =+ "nelson";

  • 正如许多其他人指出的那样,正确的运算符是+==

要设置初始值,请执行以下操作

演示:jsFiddle

HTML

<input type="text" id="teste" maxlength="50" />
<select id="select-people" onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

JS

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

window.onload=function(){
    document.getElementById('teste').value = document.getElementById("select-people").value;
}
于 2013-08-09T09:30:04.853 回答
5

There's no operator =+, += is what You need.

于 2013-08-09T09:19:16.743 回答
2

首先正确的算子+=不是=+

这不起作用的原因是因为必须调用您的函数:)

让闭包立即运行:

(function nelson(){
    document.getElementById('teste').value += "nelson"; 
})();

或没有任何function

document.getElementById('teste').value += "nelson";

或在任何地方调用它:

nelson();
于 2013-08-09T09:22:45.057 回答
1

你 id 错了,=+改成+=.

尝试使用推荐事件select。它是change

<input type="text" id="teste" maxlength="50">
<select onchange="nelson(this.value);">
  <option>nelson</option>
</select>

和 JS

function nelson(value){
  document.getElementById('teste').value += value; 
}
于 2013-08-09T09:25:47.623 回答
1

这是您的完整工作解决方案,它将与您的代码一起使用

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<input type="text" id="teste" value="" />

    <select onchange="nelson()" id="sel_nel">
      <option value="">select</option>
      <option value="nelson">nelson</option>
    </select>


<script>
    function nelson(){              
      document.getElementById('teste').value = document.getElementById('sel_nel').value; 
    }
</script>
</body>
</html>
于 2013-08-09T09:43:36.573 回答
0

看看这个小提琴:我假设您想根据select-tag 中的选择来更改文本输入的值。

--> http://jsfiddle.net/mQyLG/2/

更新(说明):

  1. 我直接设置的值select。如果你真的是这个意思+=,你可以把它改成input.value = select.value.
  2. 我对每个onchange单独select的. 像这样可以节省大量代码;)onclickoption
  3. 我在开始时调用该方法一次以确保有一个初始值。
  4. 我将函数的范围更改为 match window。这不是最好的主意,应该适合您的实际范围。
于 2013-08-09T09:29:31.847 回答