为什么addEventListener不能处理datalist?

时间:2016-05-29 06:02:44

标签: javascript

HTML

//C# 6.0 way
var g1 = parent?.child?.child?.child; 
if (g1 != null) // TODO

//C# 5.0 way
var g1 =   parent.elvisExtension().child.elvisExtension().child.elvisExtension().child; 
if (g1 != null) // TODO

JS

<input type="text" list="countries" name="mycountry" />
<datalist id="countries">
  <option value="India">India</option>
  <option value="United States">United States</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Germany">Germany</option>
  <option value="France">France</option>
</datalist>

我希望当列表选项选择时,警报框会显示该值。

1 个答案:

答案 0 :(得分:3)

您需要将侦听器绑定到输入元素

&#13;
&#13;
var a = document.getElementsByName('mycountry')[0];
a.addEventListener('change', function() {
  alert(this.value);
});
&#13;
<input type="text" list="countries" name="mycountry" />
<datalist id="countries">
  <option value="India">India</option>
  <option value="United States">United States</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Germany">Germany</option>
  <option value="France">France</option>
</datalist>
&#13;
&#13;
&#13;