簡體   English   中英

JavaScript函數導入無法正常工作

[英]JavaScript function importing doesn't work properly

我指的是下面的代碼。 https://github.com/jonasschmedtmann/complete-javascript-course/blob/master/9-forkify/final/src/js/views/searchView.js

我制作了一個函數,並嘗試將該函數導入另一個js文件,但是它不起作用。 如果我寫“ elements.searchInput.value;” 如果我執行“ console.log(elements.searchInput.value)”,它將無法正常工作。 我在做與參考文件完全相同的操作,只是想知道為什么我的代碼不起作用。

index.js

import "./../styles/style.scss";
import Search from './models/Search';
import * as searchView from './views/SearchView';
import { key, proxy } from './config';
import { elements } from './views/Base';

const state = {};

const controlSearch = async () => {
    const query = searchView.getInput(); // <- This doesn't work
    console.log(query) // Get nothing

    if(query) { // <- Can't get in to this part
        state.search = new Search(query);
        console.log("New Search", state);
    }
}

elements.searchForm.addEventListener('submit', e => {
    event.preventDefault();
    controlSearch();
});

searchView.js

import { elements } from './base';

export const getInput = () => {
    elements.searchInput.value; // This code won't show up in controlSearch function

export const clearInput = () => {
    elements.searchInput.value = '';
};
base.js

export const elements = {
    searchForm: document.querySelector('.search'),
    searchResult: document.querySelector('.movie_list'),
    searchInput: document.querySelector('.search__field')
}
Search.js

import { key } from '../config';

export default class Search {
    constructor(query) {
        this.query = query;
    }

    async getResults() {
        try {
            const res = await axios(`http://`);
            this.result = res.data.results;
        }

        catch (error) {
            alert(error);
        }
    }

}

Getter函數必須返回一個值。

const yourFunction = () => { return yourVariable };

或使用箭頭功能可以使用:

const yourFunction = () => yourVariable;

這是你的問題

export const getInput = () => {
    elements.searchInput.value; 

您沒有返回任何更改

export const getInput = () => elements.searchInput.value; 

要么

export const getInput = () => {
    return elements.searchInput.value; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM