简体   繁体   English

将参数传递给javascript函数

[英]passing arguments to a javascript function

This is a javascript function 这是一个javascript函数

<script>
function func1(var g){
alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

how to pass value 0 from function call to function definition above. 如何从函数调用向上面的函数定义传递值0。

<p onmouseover="func1(0)";>First para</p>

Change it to 更改为

<script>
function func1(g){
  alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

You need to see console log for relevant errors that pop up. 您需要查看控制台日志中弹出的相关错误。

In this case you are declaring variable in function arguments which is not allowed, you can find out more about function here . 在这种情况下,您要在函数参数中声明变量,这是不允许的,您可以在此处找到有关function更多信息。

Since you're using [0] to target the first paragraph when you mouseover it your function should be; 由于您将[0]用作鼠标悬停在第一段的目标,因此您的功能应该是;

function func1(g){
  alert(document.getElementsByTagName('p')[g].innerHTML);
}

A more canonical JS approach is to attach an event listener to your elements with JavaScript instead of inlining the code: 更为规范的JS方法是使用JavaScript将事件侦听器附加到您的元素上,而不是内联代码:

var paras = document.getElementsByTagName('p');

[].slice.call(paras).forEach(function (el, i) {
  el.addEventListener('mouseover', func1.bind(func1, i), false);
});

function func1(g){
  console.log(paras[g].innerHTML);
}

DEMO DEMO

But perhaps the best way is to use event delegation so that you're not adding listeners to all the elements. 但是也许最好的方法是使用事件委托,这样就不会在所有元素上添加侦听器。 Add an event listener to a parent element and catch the events from the paras as they bubble up the DOM: 将事件侦听器添加到父元素,并在paras冒起DOM时从paras中捕获事件:

var div = document.getElementById('paras');

div.addEventListener('mouseover', func1, false);

function func1(e) {
  var el = e.target;
  if (el.nodeType === 1 && el.nodeName === 'P') {
    console.log(el.innerHTML);
  }
}

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM