2012-07-18 129 views
-1

我在jQuery的下面的代码:如何元素添加到使用前一个元素(追加)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); 

}); } 

,但它不正确追加元素我的意思是,当我变“简单1”,这说明第二个组合框与“xyz”,但当我再次单击它显示我双附加元素我想只显示一次,当我改变组合框的值。

+0

详情如果您想追加,那么你需要使用,例如,'.append(ABC + XYZ)'。你使用的'.html()'函数*替换现有的内容。 – 2012-07-18 13:36:42

+0

@AndrewPeacock:为了公平地对待我们的OP,实际上只有一个问题有一个好的答案让他们接受 - 一个即将被关闭,其他人对upvotes没有任何答案。 – 2012-07-18 13:39:16

+0

@Cory只是一个自动反应= /倾向于不太多调查。但'.append()'将解决这个问题。 – 2012-07-18 13:41:02

回答

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>"); 
    
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,更在jquery website

相关问题