【问题标题】:Change which variable is added to in a function更改在函数中添加的变量
【发布时间】:2019-07-23 17:49:51
【问题描述】:

我很难理解如何更改函数中要添加的变量。

本质上,当用户选择酒店时,需要将其添加到hotelSelection。当他们点击下一步时,它会更新带有餐厅的地图,当他们选择餐厅时,它需要进入餐厅选择。这就是我坚持的一点,将其从酒店选择改为餐厅选择。

这是一个sn-p:

var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";

function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    hotelSelection = `<div class="input-group" id="Hotel-chosen">
                                <li class="list-group-item"> 
                      <strong>${locationName.innerHTML}</strong><br>`;

    var locationRating = document.getElementById('locationRating-' + 
    resultIndex);

    hotelSelection += `rating: ${locationRating.innerHTML}</li>`

    console.log("Hotel Selection: " + hotelSelection);

}

任何帮助将不胜感激!

【问题讨论】:

  • 我认为我们需要更多的上下文。这个函数是怎么调用的? resultIndex来自哪里?
  • 不幸的是,您的功能相当具体。我猜你最好有一个不可知的选择变量,以及 type 的附加参数(酒店、餐厅)等,并将函数应用于每个选择,如第二部分所示下面的答案。 此注释假定 HTML 对于每个选择都存在根本不同

标签: javascript arrays function variables


【解决方案1】:

这触及了函数如何通信的核心。您正在做的是在更高的“闭包”中访问变量。这有其优点和缺点,而您现在发现的缺点之一是它不是很灵活。

如果您不采用这种方式,而是能够使用函数的返回值,那么您将可以灵活地执行您所说的操作。例如:

var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";

function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    var selection = `<div class="input-group" id="Hotel-chosen">
                                <li class="list-group-item"> 
                      <strong>${locationName.innerHTML}</strong><br>`;

    var locationRating = document.getElementById('locationRating-' + 
    resultIndex);

    selection += `rating: ${locationRating.innerHTML}</li>`

    console.log("Hotel Selection: " + hotelSelection);
    return selection;
}

如果你这样做,那么当你调用函数时,你只需将返回值分配给一个变量,如下所示:

hotelSelection = chooseSelection(someIndex);
sightSelections = chooseSelection(someIndex);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多