Programing

HTML 버튼을 사용하여 JavaScript 함수 호출

lottogame 2020. 4. 30. 07:26
반응형

HTML 버튼을 사용하여 JavaScript 함수 호출


JavaScript 버튼을 사용하여 JavaScript 함수를 호출하려고합니다.

코드는 다음과 같습니다.

<input type="button" value="Capacity Chart" onclick="CapacityChart();">

그래도 제대로 작동하지 않는 것 같습니다. 더 좋은 방법이 있습니까?

링크는 다음과 같습니다. http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html 왼쪽 하단 섹션에서 용량 탭을 클릭하십시오. 값이 변경되지 않으면 버튼이 경고를 생성하고 값을 입력하면 차트를 생성해야합니다.


HTML / DOM으로 이벤트를 처리하는 몇 가지 방법이 있습니다. 옳고 그른 방법은 없지만 상황에 따라 다른 방법이 유용합니다.

1 : HTML에 정의되어 있습니다.

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

2 : 자바 스크립트로 이벤트의 DOM 속성에 추가했습니다.

//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;

//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };

3 : Javascript를 사용하여 이벤트 핸들러에 함수를 첨부합니다.

var el = document.getElementById("clickMe");
if (el.addEventListener)
    el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
    el.attachEvent('onclick', doFunction);

두 번째 및 세 번째 메소드는 모두 인라인 / 익명 함수를 허용하며 요소가 문서에서 구문 분석 된 후에 선언되어야합니다. onclick 속성이 XHTML 사양에 없기 때문에 첫 번째 방법은 유효한 XHTML이 아닙니다.

첫 번째와 두 번째 방법은 상호 배타적이므로 하나 (두 번째)를 사용하면 다른 하나 (1)를 무시합니다. 세 번째 메소드를 사용하면 첫 번째 또는 두 번째 메소드도 사용 된 경우에도 동일한 이벤트 핸들러에 원하는만큼 많은 함수를 첨부 할 수 있습니다.

대부분의 경우 문제는 CapacityChart()함수의 어딘가에 있습니다. 링크를 방문하여 스크립트를 실행하면 CapacityChart () 함수가 실행되고 두 개의 팝업이 열립니다 (하나는 스크립트에 따라 닫힙니다). 다음 줄이있는 경우 :

CapacityWindow.document.write(s);

대신 다음을 시도하십시오.

CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();

편집
코드를 보았을 때 IE 용으로 특별히 작성했다고 생각했습니다. 다른 언급로서 당신은 참조를 교체해야합니다 document.all으로 document.getElementById. 그러나이 후에도 스크립트를 수정하는 작업을 계속해야하므로 크로스 브라우저에서 작동하도록 코드를 변경하는 실수가 더 혼란을 줄 수 있으므로 적어도 IE에서 먼저 작동시키는 것이 좋습니다. 일단 IE에서 작동하면 코드를 업데이트하는 동안 다른 브라우저에서 작동하는지 쉽게 알 수 있습니다.


나는 눈에 거슬리지 않게 자바 스크립트를 추가하는 것이 더 좋을 것이라고 말하고 싶습니다 ...

jQuery를 사용하면 다음과 같은 작업을 수행 할 수 있습니다.

<script>
  $(document).ready(function(){
    $('#MyButton').click(function(){
       CapacityChart();
    });
  });
</script>

<input type="button" value="Capacity Chart" id="MyButton" >

HTML과 버튼에서 함수를 호출하는 방식이 올바르게 보입니다.

The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.

Edit:

Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value


This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code


Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.

So it should just look like this: onclick="CapacityChart()"

then it all should work :)


One major problem you have is that you're using browser sniffing for no good reason:

if(navigator.appName == 'Netscape')
    {
      vesdiameter  = document.forms['Volume'].elements['VesDiameter'].value;
      // more stuff snipped
    }
    else
    {
      vesdiameter  = eval(document.all.Volume.VesDiameter.value);
      // more stuff snipped
    }

I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?

The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:

<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">

Either give them a name and use the elements array, or (better) use

var vesdiameter = document.getElementById("VesDiameter").value;

which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:

if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
    // do stuff...
}

You probably want to validate your input as well; something like

var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
    alert("Diameter should be numeric");
    return;
}

would help.


Your code is failing on this line:

var RUnits = Math.abs(document.all.Capacity.RUnits.value);

i tried stepping though it with firebug and it fails there. that should help you figure out the problem.

you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.


I have an intelligent function-call-backing button code:

<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

silly way:

onclick="javascript:CapacityChart();"

You should read about discrete javascript, and use a frameworks bind method to bind callbacks to dom events.

참고URL : https://stackoverflow.com/questions/1947263/using-an-html-button-to-call-a-javascript-function

반응형