gpt4 book ai didi

javascript - 为什么这个 'feelings' 显示为一个对象而不是我在文本字段中输入的内容?

转载 作者:行者123 更新时间:2023-12-04 09:34:41 24 4
gpt4 key购买 nike

  • 当我 console.log(feelings) 它打印输入的文本值
    形式。
  • 但是,当我尝试向对象添加“感觉”并进行更新时
    使用它的 ui 我得到 [object Object]
  • 当你使用感觉时,值(value)下降
    在异步代码中它工作得很好。不是感觉。值(value)===
    .value.value??
  • <div class ="holder zip">
    <label for="zip">Enter Zipcode here</label>
    <input type="text" id="zip" placeholder="enter zip code here">
    </div>
    <div class ="holder feel">
    <label for="feelings">How are you feeling today?</label>
    <textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="9" cols="50"></textarea>
    <button id="generate" type = "submit"> Generate </button>
    </div>

    function generate (e) {
    const zipcode = document.querySelector('#zip').value;
    const feelings = document.querySelector('#feelings').value;
    console.log(zipcode)
    console.log(feelings)

    getWeather(baseURL+zipcode+apiKey)
    .then(function(data){
    postData(data)
    })
    .then(updateUI)
    }
    /* Function to GET Web API Data*/
    const getWeather = async (url = '') => {
    const response = await fetch(url);

    try {
    const weatherData = await response.json();
    weatherData['date'] = newDate;
    weatherData['feelings'] = feelings; //where it displays as an {} unless use feelings.value
    console.log(weatherData);
    return weatherData;

    } catch(error){
    console.log('error', error);
    }
    }



    最佳答案

    feelings不只是任何随机对象,它是您的 textarea元素。这种奇怪的行为是 chrome 和其他一些浏览器的一个不好的特性;他们将带有 id 的 DOM 元素分配给以 id 命名的全局变量,在另一个 SO 问题上阅读更多相关信息:Do DOM tree elements with ids become global variables?
    既然你没有通过 feelings来自 generategetWeather , feelings used 是浏览器创建的全局变量,它是 DOM 元素,一个对象。换句话说,全局变量 feelings不是 shadowed ,所以被使用。
    要解决此问题,只需通过 feelings作为来自 generate 的参数至 getWeather像这样:

    function generate (e) {
    //...
    getWeather(baseURL + zipcode + apiKey, feelings)
    // ...
    }

    const getWeather = async (url, feelings) => {
    // here the parameter 'feelings' is used rather than the global variable 'feelings'.
    }

    关于javascript - 为什么这个 'feelings' 显示为一个对象而不是我在文本字段中输入的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62648698/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com