点击事件返回未定义的函数。

huangapple go评论63阅读模式
英文:

onclick event returns undefined function

问题

我正在构建一个演示电影应用程序,因此我决定为目标链接分配一个带有获取一些与电影相关数据的函数的onclick事件。
当我点击我想要处理的目标链接时,出现了一个问题,返回给我一个未定义的函数。
以下是代码:

function getMovieList(key, value) { console.log(key, value)}

function getLanguages() {
    const languagesList = document.querySelector("[languages]");

    const languagesArray = [
        ["en-US", "english"],
        ["it", "italian"],
        ["de", "german"],
        ["hi", "indian"],
    ];

    const languagesMap = new Map();

    languagesArray.forEach(languages => {
        const [idLanguage, language] = languages;
        languagesMap.set(idLanguage, language);

        languagesList.innerHTML += `
            <li class="capitalize" onclick="getMovieList(with_original_langauge=${idLanguage}, ${language})">
                <a href="index.html" language-id=${idLanguage}>${language}</a>
            </li>
        `;
    });
}

getLanguages();

当我检查我的链接时,它们确实具有给定的参数,但如果我点击它们,它会说我的函数未定义,所以我无法获取值。
为什么会这样?

我尝试使用window.onload方法,希望预先加载函数并将其定义,但仍然没有起作用。

英文:

I am building a demo movie app so I decided to assign onclick events with a function that gets me some movie related data.
The problem arises when I click on the target links I want to work on, giving me back an undefined function.
Here's the code:

    function getMovieList(key,value) { console.log(key,value)}
    
    function getLanguages() {
        const languagesList = document.querySelector(&quot;[languages]&quot;);
        
        const languagesArray = [
            [&quot;en-US&quot;, &quot;english&quot;],
            [&quot;it&quot;, &quot;italian&quot;],
            [&quot;de&quot;, &quot;german&quot;],
            [&quot;hi&quot;, &quot;indian&quot;],
        ];
    
        const languagesMap = new Map();
    
        languagesArray.forEach( languages =&gt; {
            const [idLanguage,language] = languages;
            languagesMap.set(idLanguage,language);
    
            languagesList.innerHTML += `
             &lt;li class=&quot;capitalize&quot; onclick=&quot;getMovieList(with_original_langauge=${idLanguage}, ${language})&quot;&gt;
                &lt;a href=&quot;index.html&quot; language-id=${idLanguage}&quot;&gt;${language}&lt;/a&gt;
            &lt;/li&gt;
        `;
       
        } );
    }
getLanguages()

When I inspect my links they do have the given arguments but if I click on them, then it says my function is undefined so I cannot get the values back.
Why is that ?

I tried the method window.onload expecting to load the function beforehand and get it as defined,but still it did not work.

答案1

得分: 1

The getMovieList() function is called asynchronously, which means that the default behavior of the <a> link is called before the function is executed.

Use event.preventDefault(); in the event handler, and change the href manually from the function body.

function getMovieList() {
  alert('movie list');
  location.href = "index.html";
}
<li>
  <a href="index.html" onclick="event.preventDefault(); getMovieList()">language</a>
</li>
英文:

The getMovieList() function is called asynchronously, which means that the default behaviour of the &lt;a&gt; link is called before the function is executed.

Use event.preventDefault(); in the event handler, and change the href manually from the function body.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function getMovieList() {
  alert(&#39;movie list&#39;);
  location.href=&quot;index.html&quot;;
  }

<!-- language: lang-html -->

&lt;li&gt;
   &lt;a href=&quot;index.html&quot; onclick=&quot;event.preventDefault();getMovieList()&quot;&gt;language&lt;/a&gt;
&lt;/li&gt;

<!-- end snippet -->

答案2

得分: 0

以下是您提供的内容的中文翻译:

编辑:自您的编辑后,我的答案已更改!

有一些内容查看您的代码,但您必须在函数中添加一个真正的location.href

在这里,它只是为演示目的显示一些URL参数的警告。

let languagesListDiv;

let languagesArray = [
    ["en", "英语"],
    ["it", "意大利语"],
    ["de", "德语"],
    ["hi", "印度语"]
];

let languagesMap = new Map();
let result = "";

window.addEventListener("DOMContentLoaded", run);

function getMovieList(key, value) {
    console.log("key = " + key + ", value = " + value)
}

function alertMovieList(key, value) {
    alert("location.href=\"http://yourLinkHere.test?key=" + key + "&value=" + value + "\"")
}

function run(e) {
    languagesListDiv = document.getElementById("languagesListDiv");
    getLanguages();
}

function getLanguages() {
    languagesArray.forEach(languages => {
        languagesListDiv.innerHTML += `<li class="capitalize"><a href="index.html"  onclick="event.preventDefault();alertMovieList('${languages[0]}','${languages[1]}')">
        key = ${languages[0]}, value = ${languages[1]}</a></li>`;
        getMovieList(languages[0], languages[1]);
    });
}
<ul id="languagesListDiv">

</ul>

请注意,我只翻译了代码中的文本部分,不包括代码本身。

英文:

EDIT : My answer have changed since your edit!

There's something that looks at your code but you have to add a real location.href in the function.

Here it makes just an alert with some URL parameters for the demo.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

	let languagesListDiv;
        
    let languagesArray = [
			[&quot;en&quot;, &quot;english&quot;],
			[&quot;it&quot;, &quot;italian&quot;],
			[&quot;de&quot;, &quot;german&quot;],
			[&quot;hi&quot;, &quot;indian&quot;]
        ];
    
    let languagesMap = new Map();
	let result = &quot;&quot;;
	
	window.addEventListener(&quot;DOMContentLoaded&quot;,run);
		
	function getMovieList(key,value){
		console.log(&quot;key = &quot; + key + &quot;, value = &quot; + value)
	}
	function alertMovieList(key,value){
		alert(&quot;location.href=\&quot;http://yourLinkHere.test?key=&quot; + key + &quot;&amp;value=&quot; + value + &quot;\&quot;&quot;)
	}
    function run(e){
		languagesListDiv = document.getElementById(&quot;languagesListDiv&quot;);
		getLanguages();
	}
    function getLanguages() {
    languagesArray.forEach( languages =&gt; {
	languagesListDiv.innerHTML += `&lt;li class=&quot;capitalize&quot;&gt;&lt;a href=&quot;index.html&quot;  onclick=&quot;event.preventDefault();alertMovieList(&#39;${languages[0]}&#39;,&#39;${languages[1]}&#39;)&quot;&gt;key = ${languages[0]}, value = ${languages[1]}&lt;/a&gt;&lt;/li&gt;`;
	getMovieList(languages[0],languages[1]);
        });
    }

<!-- language: lang-html -->

&lt;ul id=&quot;languagesListDiv&quot;&gt;
	
&lt;/ul&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月19日 18:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定