2016-07-10 2 views
-2

주어진 데이터를 다른 입력 데이터로 곱하는 JS 함수가 있습니다.페이지를 처음로드 할 때 어떻게 자바 스크립트 코드를 실행합니까?

var item1unitp = 150; 
var item2unitp = 320; 

function total() { 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 

    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 

    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
} 

내 HTML

Item 1 : <input type="text" id="t1" value="1" onkeyup="total();"/> <br/><br/> 

Item 2 : <input type="text" id="t2" value="1" onkeyup="total();"/> <br/><br/> 

Sub Total : <span id="tot"></span> 

이 코드가 작동되지만 페이지의 시작 부분에이 범위는 아무것도 표시되지 않습니다. 그러나 이미 각 입력에 1을 더했습니다. 처음 부분 부분을 어떻게 얻습니까?

+3

당신은 더 구체적으로 ?? – adeneo

+0

의 요소 수'총을 추가하여 기능을 실행

https://jsfiddle.net/y5pgrcc4/

+1

가장 간단한 방법은 ''태그 바로 앞에 두는 것입니다 : '' –

답변

1

나는 그것이 틀렸다는 것을 알려주기를 기대하고있다.

Sub Total : <span id="tot" value="total()"></span> 
<script> 
var item1unitp = 150; 
var item2unitp = 320; 

function total() { 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 
    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 
    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
    return tot; 
} 
total(); 
</script> 
1

시도해보십시오. 페이지가로드 될 때 함수 total이 호출되도록 설정합니다. HTML 대신 JS에서 이벤트 핸들러를 onkeyup으로 설정하는 것도 좋은 습관입니다. 이것은 레이아웃과 웹 사이트의 동작을 분리하기위한 것이기 때문에 그렇게했습니다.

HTML

Item 1 : <input type="text" id="t1" value="1" /> <br/> <br/> 
Item 2 : <input type="text" id="t2" value="1" /> <br/> <br/> 
Sub Total : <span id="tot"></span> 

JS

var item1unitp = 150; 
var item2unitp = 320; 

t1.onkeyup = total; 
t2.onkeyup = total; 
window.onload = total; 

function total(){ 

    var x1 = document.getElementById('t1').value; 
    var x1p = parseInt(x1); 
    var tot1 = item1unitp * x1p; 

    var x2 = document.getElementById('t2').value; 
    var x2p = parseInt(x2); 
    var tot2 = item2unitp * x2p; 

    var tot = tot1+tot2; 

    document.getElementById('tot').innerHTML = tot; 
} 
그냥()`어딘가에 ** 후 ** DOM을
관련 문제