如何使用Jquery重写此Javascript代码?

时间:2009-12-27 03:01:30

标签: javascript jquery

function SelectDistrict(argument)
{ 
var sel=document.getElementById("city");
sel.style.display = '';
sel.options.length = 0;

sel.options.add(new Option('Please select a location',''));

var i=1;
var tempInt=parseInt(argument);
if (tempInt%10000==0)
{
var place1=document.getElementById('place1');
 place1.innerHTML =county[tempInt];
}

sel.options.add(new Option('all',tempInt));

$('#inputcity').hide();
while (i<=52)
{
    tempInt+=100;

    if (county[tempInt]==undefined)
    { 
        break;
    }
    else { 

    op_cir = new Option(county[tempInt], tempInt);
            sel.options.add(op_cir);

    }
i++;    
    }

}

3 个答案:

答案 0 :(得分:2)

你可以这样做:

function SelectDistrict(argument)
{
    var sel = $('#city'); // Store the jQuery object to save time
    sel.hide().empty().append('<option>Please select a location.</option');
    var i = 1;
    var tempInt = argument;
    if (tempInt % 10000 == 0)
    {
        $('#place1').html(county[tempInt]);
    }
    sel.append('<option value="'+tempInt+'">all</option>');
    $('#inputcity').hide();
    var optionsValue = ''; // Appending strings to each other is faster than modifying the DOM
    tempInt += 100;
    while ((i <= 52) && (county[tempInt] != undefined)) // Just put the condition here instead of breaking the loop
    {
        optionsValue += "<option value='" + tempInt + "'>" + county[tempInt] + "</option>";
        tempInt += 100;
        i++;
    }
    sel.append(optionsValue);
}

我希望这适合你!

答案 1 :(得分:0)

你必须用$(“#elementid”)替换每个document.getElementById(),如$(“#city”);

和place1.innerHTML = county [tempInt]; by $(“#place1”)。text(county [tempInt]);

答案 2 :(得分:0)

您可以将while循环更改为:

$.each(county, function(i, itm) {
     optionsValue += "<option value='" + i + "'>" + itm + "</option>";
})