This article summarizes the problems encountered in development projects
Question 1: How to select the value in the option of select?
First, a method onchange() will be used; this method is mainly used to trigger the time when the content of the selection box changes
Implementation code:
<!doctype html> <html> <head lang="en"> <meta charset="UTF-8"> </head> <body> <select onchange="test(event)"> <option>安静</option> <option>晴天</option> <option>七里香</option> </select> <script type="text/javascript"> function test (e) { var e = event ? event : window.event; alert(e.target.value); } </script> </body> </html>
Question 2: But in development, we usually select the content just for display, and what we really need to do is to interact with the background and transmit data. At this time In order to reduce http data transmission as much as possible, we usually pass id and so on as the data transmission flag. How to do this?
In development, options are generally created dynamically, so at this time, we only need to dynamically create a custom attribute for you. So how do you get custom properties?
<!doctype html> <html> <head lang="en"> <meta charset="UTF-8"> </head> <body> <select onchange="test(event)" id="sel"></select> <script type="text/javascript"> //定义内容的json数据,一般从后台获取 var data = [ { name: '晴天', id: '1' }, { name: '安静', id: '2' }, { name: '七里香', id: '3' } ]; createOption('sel',data); //创建option function createOption(parentId, data){ var parentId = document.getElementById(parentId); for(var i=0; i<data.length; i++){ var opt = document.createElement('option'); //设置option的值 opt.innerHTML = data[i].name; //定义option的自定义值 opt.setAttribute('dataid', data[i].id); parentId.appendChild(opt); } } //选取自定义属性的方法 function test (e) { var e = event ? event : window.event; var target = e.target; var index = target.selectedIndex; alert("我的id="+target[index].getAttribute('dataid')); } </script> </body> </html>
The results are as follows:
This is the problem I encountered during development. I hope it can inspire everyone's learning.