从Javascript函数获取值以显示在其他位置

时间:2012-03-14 16:21:54

标签: javascript

我有一个函数可以计算用户选择的门票数量(从下拉列表中)并将其乘以门票的价格(此门票价格存储在我的sql数据库中)。

函数本身工作正常:

function quantityChange(selElem) {
//Select the value of the drop down list       
var quantity = $('#showQuantity option:selected').val();
//get the value of the number from the tPrice column in 'ticket' table
var ticket = parseInt(document.getElementById('ticketPriceHidden').value);
//get the venue value
var venue = document.getElementById('venuePlaceHidden').value;
//multiply them together
var total = quantity * ticket;

document.getElementById('summary').innerHTML= 'You have chosen'+ ' ' + quantity + ' ' + 'tickets @' + ' ' + venue + ' = ' + ' ' + ' £' + total;
}

这个函数在一个名为'ticket'的div中调用,一旦用户从这个函数中看到计算出的总数,然后他们按下一个隐藏这个div的“继续”按钮并显示一个名为“delivery”的新div,所以结果不被丢弃。

我想要做的是:我想再次获得函数quantityChange(selElem)的结果,但是在一个名为'summary'的全新div中。有没有办法做到这一点?

非常感谢任何帮助,谢谢。

3 个答案:

答案 0 :(得分:1)

一个选项是将您希望文本显示的元素的ID作为参数传递给函数:

function quantityChange(elementId) {
    //Select the value of the drop down list       
    var quantity = $('#showQuantity option:selected').val();
    //get the value of the number from the tPrice column in 'ticket' table
    var ticket = +$('#ticketPriceHidden').val();
    //get the venue value
    var venue = $('#venuePlaceHidden').val();
    //multiply them together
    var total = quantity * ticket;

    $('#' + elementId').html('You have chosen'+ ' ' + quantity + ' ' + 'tickets @' + ' ' + venue + ' = ' + ' ' + ' £' + total);
}

你称之为:

quantityChange('summary');

为了获得更大的灵活性,您可以返回所有计算值:

function quantityChange() {
    //Select the value of the drop down list       
    var quantity = $('#showQuantity option:selected').val();
    //get the value of the number from the tPrice column in 'ticket' table
    var ticket = +$('#ticketPriceHidden').val();
    //get the venue value
    var venue = $('#venuePlaceHidden').val();
    //multiply them together
    var total = quantity * ticket;

    return {
        venue: venue,
        quantity: quantity,
        ticket: ticket,
        total: total
    };
}

并在调用函数中创建输出:

var data = quantityChange();

$('#summary').text('You have to pay ' + data.total + ' something');

这样,实际输出(你想如何呈现数据)不会在计算值的函数中进行硬编码。

答案 1 :(得分:0)

使其成为返回值的通用函数。

function foo()
{
var a = 0;
var b = 1;
return a+b;
}

document.getElementById("bar").innerHTML = "Your returned amount is " + foo();

bar的innerHTML会读取

Your returned amount is 1

答案 2 :(得分:0)

这些行应该对你有帮助。

第一行创建一个div。

第二行将函数结果插入该div。

第三行将div挂在你给出id为“xxx”的元素上。

var div = document.createElement("div");
div.innerHTML = functionResult;
document.getElementById("xxx").appendChild(div);
相关问题