如何使用onclick

时间:2017-03-28 12:24:13

标签: javascript function variables onclick

我尝试使用html中的onclick函数将变量从0更改为4。以下是我所拥有的。 javascript / HTML:



function openTab(evt, page) 
{
    var i, pages, links;
    //hide all pages
    pages = document.getElementsByClassName("content");
    for (i = 0; i < pages.length; i++) {
        pages[i].style.display = "none";
    }
    //remove active tab
    links = document.getElementsByClassName("link");
    for (i = 0; i < links.length; i++) {
        links[i].className = links[i].className.replace(" active", "");
        }
    //set active page and tab
    document.getElementById(page).style.display = "block";
    evt.currentTarget.className += " active";
}

var y=0; 
var x=10; 
var hp=x-y 
var changeVariable = function(){ 
    alert("before : "+y) 
    y = 4; 
    alert("after : "+y);
//adding result to element
document.getElementById("myResult").innerHTML = hp;
}
//binding click onto element 
document.getElementByid("clickMe").addEventListener("click", changeVariable );
&#13;
  <button Id="clickMe">
 click me ! 
</button>
<div  id="myResult">
</div>
&#13;
&#13;
&#13;

javascript的顶部是我页面上的标签

3 个答案:

答案 0 :(得分:0)

<a href="action" onclick="y=4"> click </a>

这个可能有用。

答案 1 :(得分:0)

Onclick只需调用一个更新y值并将新值作为参数传递的函数

例如:

<html>
<body>
 <a href="action" onclick="updateValue(4);"> click </a>
</body>
<script>
 var y=0;
 var x=10;
 var h=x-y
 function updateValue(newValue){
    y = newValue;
 }
</script>
</html>

答案 2 :(得分:0)

您应该避免使用内联事件处理程序,因为使用它们是一种不好的做法。你可以像这样实现你想做的事情

document.addEventListener("DOMContentLoaded", function(event) { 
  var y=0;
  var x=10;
  var h=x-y;

document.getElementById("myResult").innerHTML = h;

var changeVariable = function(){
 y = 4;
 h = x - y;
 //Adding the result to an element
 document.getElementById("myResult").innerHTML = h;
}

//Binding "click" on an element

  document.getElementById("clickMe").addEventListener("click", changeVariable);
});
 
<button id="clickMe">
  click me !
</button>
<div id="myResult">
</div>