简体   繁体   English

下拉菜单的HTML和Javascript(jquery)行为

[英]HTML and Javascript(jquery) behaviour of drop down menus

In the following fiddle, I used both html and javascript to manipulate a drop-down list. 在下面的小提琴中,我同时使用了html和javascript来操纵一个下拉列表。 Both with the same ID, however the javascript code is not working, is there something wrong with it? 两者具有相同的ID,但是javascript代码无法正常工作,这有什么问题吗?

https://jsfiddle.net/a2owoszc/4/ https://jsfiddle.net/a2owoszc/4/

This is the js code: 这是js代码:

var options = ["1", "2", "3", "4", "5"];
var $el = $("#example");
$el.empty();
$el.each(options, function(i, p) {
    $el.append($('<option></option>').val(p).html(p));
});

In addition, how would you explain the behavior of the dropdown list? 此外,您如何解释下拉列表的行为? Will the values change to the values specified in JS or stay the same as the values specified in HTML code, and why? 值将更改为JS中指定的值还是与HTML代码中指定的值相同,为什么?

Check this, 检查一下

 $(document).ready(function() { var options = ["1", "2", "3", "4", "5"]; var $el = $("#example"); $el.empty(); $.each(options, function(i, p) { $el.append($('<option></option>').val(p).html(p)); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="example"> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> </select> 

You had mistake in this line $el.each(options, function(i, p) { which is not syntax of $.each function 您在此行中出错$el.each(options, function(i, p) {这不是$ .each函数的语法

Here is the working jsfiddle: 这是工作的jsfiddle:

https://jsfiddle.net/78dkd9mf/ https://jsfiddle.net/78dkd9mf/

And here the code: 这里的代码:

var options = ["1", "2", "3", "4", "5"];
var $el = $("#example");
$el.empty();
$.each(options, function(i, p) {
    $el.append($('<option></option>').val(p).html(p));
});

Also I think you forgot to link to the jquery plugin in the JSFiddle. 我也认为您忘记了链接到JSFiddle中的jquery插件。

Another simple way to do it. 另一种简单的方法。

$(function(){ 
  var options = ["1", "2", "3", "4", "5"];
  var $el = $("#example");
  $el.empty();

  options.forEach((option) => {
    $el.append($('<option></option>').val(option).html(option));
  });

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM