在选择中添加选项并将数据属性添加到选项

时间:2017-12-15 06:53:42

标签: javascript jquery

我有选择名称slc_pc,我想通过jquery代码附加选项。

我尝试这些脚本。但它不起作用。

$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true).attr("abc",brand,"123",model));

4 个答案:

答案 0 :(得分:1)

如果您在select元素中添加ID“slc-pc”,就像它的基本形式一样:

kUTTypeMovie

答案 1 :(得分:1)

尝试这个

您已在import kivy from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import StringProperty, ObjectProperty, ListProperty from kivy.uix.listview import ListItemButton from kivy.adapters.listadapter import ListAdapter class DemoScreen1(Screen): pass class DemoScreen2(Screen): labText = StringProperty() def labelUpdater(self,newText): self.ids.labText.text = newText class MyListButton(ListItemButton): data = ListProperty() class MyListAdapter(ListAdapter): scr = ObjectProperty() def on_selection_change(self, *args): self.scr.ChangeScreen(self.selection[0].index) class AppScreenManager(ScreenManager): def ChangeScreen(self, option): if option == 0: print("Screen1") self.ids.screen2.labelUpdater("Screen 1 was pressed") else: print("Screen2") self.ids.screen2.labelUpdater("Screen 2 was pressed") self.current = "demoscreen2" class Tester(App): pass if __name__ == '__main__': Tester().run() 之后添加),并从上次删除(new Option("Hello", "Hello", true, true)



)

$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true)).attr("abc", "brand", "123", "model");




答案 2 :(得分:1)



   HttpURLConnection con = Connector.connect(urlAddress);
        if (con == null) {
            return null;
        }

        try {
            InputStream is = new BufferedInputStream(con.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(is));


            }

            br.close();
            is.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

$(function(){
    var brand = 'test';
    var model = '123';
    
    var brand1 = 'abc';
    var model1 = '456';
  
   $(".slc_pc").append("<option value='hello' data-brand='" +brand+ "' data-model='" +model+ "'>hello</option><option value='hello1' data-brand='" +brand1+ "' data-model='" +model1+ "'>hello1</option>");
})

$(document).on("change",".slc_pc", function(){
   var option = $("option:selected", this);
   alert("value : "+ $(this).val() + ", brand : "+$(option).data('brand') + ", model : " + $(option).data('model'));
})
&#13;
&#13;
&#13;

可以通过类似的方式完成。

答案 3 :(得分:1)

您的代码中存在一些错误。首先,要设置多个属性,需要将它们作为对象传递。其次,data属性的属性名称和值不正确。 brand&amp; model应为财产,abc&amp; 123应分别为其值。

new Option将创建一个没有attr方法的选项元素。您可以使用jQuery创建一个新元素。

这是正确的方法

$('select[name="slc_pc"]')
    .append($('<option />')  // Create new <option> element
    .val('Hello')            // Set value as "Hello"
    .text('Hello')           // Set textContent as "Hello"
    .prop('selected', true)  // Mark it selected
    .data({                  // Set multiple data-* attributes
        brand: 'abc',
        model: '123'
    });