-1

私はjqueryに次のコードを持っています:

var qtype ="<select id='qtype'><option>qt1 </option><option>qt2</option></select>";
var abc ="<select id='t1'><option>Simple 1</option><option>Simple 2</option></select>";
var xyz ="<select id='t2'><option>Hard</option></select>";
var pqr ="<select id='t3'><option>Diff</option></select>";

$("#qttype").html(qtype);
var qtype=$("qttype"); 
if(qtype== "qt1"){
 $("#t1").change(function(){        
    $("#abc").change(function(){
     $("#divid").html(abc+xyz);
         $("#divid").html(abc+xyz+pqr);

 });  }

ただし、要素が正しく追加されません。つまり、「simple 1」を変更すると、「xyz」が付いた2番目のコンボボックスが表示されますが、もう一度クリックすると、二重に追加された要素が表示され、コンボボックスの値を変更したときに1回だけ表示します。

4

2 に答える 2

2

追加する位置の後に要素を配置した場合は、.before()を確認する必要があります。.after()も使用できますが、この場合は前の要素を選択する必要があります。

  • 例:

    $("element").before("<p>this p will be added before the 'element'</p>");
    $("element").after(" <p>this p will be added after  the 'element'</p>");
    
于 2012-07-18T13:44:36.483 に答える
1

一例として、これがお役に立てば幸いです。

$(document).ready(function(){
    $(document.body).append('<div id="abc"></div>'); // create new #abc and append it directly to body
    $('#abc').append($('<div/>').attr('id','divid').html('hello!'));
    var course = $('<select id="qtype"></select>'); // jquery object containing #qtype
    var abc = '<option value="s">Simple</option>'; // string
    var xyz = '<option value="h">Hard</option>'; // string
    var pqr = '<option value="d">Diff</option>'; // string
    course.append(abc).append(xyz).append(pqr); // triple call of .append()
    //alert("course is " + course + ",\n course[0] is " + course[0] + ' ~ ' + course[0].innerHTML);
    $('#abc').before(course); //insert <select> before #abc
    $('#qtype').change(function(){
        var str = this.options[this.selectedIndex].value;
        str += ' ~ ' + this.options[this.selectedIndex].innerHTML;
        $('#abc').html(str);
    });
});

例@ jsfiddle 、jqueryWebサイトでの詳細

于 2012-07-18T15:08:48.003 に答える