我做了以下工作,很好。它从下拉菜单更改Div onSelectChange的背景。我敢肯定有更好的方法。有人可以推荐吗?

谢谢您的光临。

$(document).ready(function() {

    $("#QuoteRequiredFor").change(onSelectChange);

});

function onSelectChange() {
    var selected = $("#QuoteRequiredFor option:selected");
    var output = "";
    if (selected.val() == '') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/images/FFheaderQuoteFactoring.jpg)');
    };
    if (selected.val() == 'Factoring') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/factoring.jpg)');
    };
    if (selected.val() == 'Mortgage') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/Mortgage.jpg)');
    };
    if (selected.val() == 'Stock') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/stock.jpg)');
    };
    if (selected.val() == 'Asset') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/asset.jpg)');
    };
    if (selected.val() == 'Invoice discounting') {
        output = "You Selected " + selected.text();
        $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/factoring.jpg)');
    };

    $("#output").html(output);
}

最佳答案

$(document).ready(function() {

    $("#QuoteRequiredFor").change(onSelectChange);

});

function onSelectChange() {
    var selected = $("#QuoteRequiredFor option:selected");
    var output = "";
    var cssValues = new Array();
    cssValues['Factoring'] = 'factoring.jpg';
    cssValues['Mortgage'] = 'Mortgage.jpg';  // same as for other values

    if(selected.val() == ''){
    output = "You Selected " + selected.text();
    $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/images/FFheaderQuoteFactoring.jpg)');
    }
    else{
    output = "You Selected " + selected.text();
    $('#FinanceQuoteForm').css('background', 'url(/Finance-Quote/FinanceQuoteForm/Images/'+cssValues[selected.val()]+')');
    }

   $("#output").html(output);
}

关于javascript - 从选择更改Div的背景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5764413/

10-11 04:13