从jQuery </select> </div>上的操作<div>到<select> / dropdown list元素返回值

时间:2011-08-11 09:30:43

标签: jquery html

这是HTML脚本

<div id="5">
<div class="niche">Click here to generate dropdownlist</div>
<div>

<div id="tests">This will change, but it won't when you change the dropdown list</div>

jQuery

var theNiche;

$('.niche').click(function(){

    var theNiche = $(this).text();   
    var createSelect = $(document.createElement('select')).attr('id', 'sel-niche');
      createSelect.appendTo(this);
    $(this).replaceWith(createSelect);

var myOptions = {
      'Autos' : 'Autos',
      'Business' : 'Business',
      'Education' : 'Education',
      'Entertainment' : 'Entertainment',
      'Fashion' : 'Fashion',         
      'Food' : 'Food',
      'Health' : 'Health',
      'Home' : 'Home',
      'Insurance' : 'Insurance',
      'Gambling' : 'Gambling',
      'General' : 'General',
      'Music' : 'Music',
      'Real Estate' : 'Real Estate',
      'Sex' : 'Sex',
      'Shopping' : 'Shopping',
      'Sports' : 'Sports',
      'Technology' : 'Technology',
      'Travel' : 'Travel'
        };
        $.each(myOptions, function(val, thetext) {
            $('#sel-niche').append(
                $('<option></option>').attr('value',val).text(thetext)
            ); 
        });

        $('#sel-niche option[value="'+theNiche+'"]').attr('selected',true);
        $('#tests').html(theNiche);   
    });

var onChange = function(e){    
    $('#5 select').change(function(){
      alert($('#5 option:selected').text());
    }).change(onChange);
};

$('#5 select').change(onChange);

当我“点击此处生成下拉列表”时,div id =“tests”的文本将会改变。但是当下拉列表显示并且我试图改变该值时。 div id =“tests”文本没有改变。

哪里是我的错误?

*这是我的第一篇文章,对不起这个烂摊子

1 个答案:

答案 0 :(得分:0)

您使用'5'作为ID。有效ID不得以(或仅仅是)数字开头。

将其更改为名称(例如“五”),您的代码将有效。