2017-02-04 2 views
0

У меня есть простая проблема с хранением и передачей переменной из одной функции в другую. Мой сценарий должен работать так:Хранение/передача переменной в другую функцию

<input type="text" id="ip1" >  
     <input type="button" id="check_button" value="checking" onclick="check_text()"> 
     <input type="button" id="write_button" value="write" onclick="write()"> 
<p id="ag"></p> 

Если кто-то вводит значение в поле ввода "ip1" и прижимает "check_button", значение должно быть сохранено в переменной. Эта переменная должна быть записана во внутреннемHTML "ag" при нажатии на кнопку "write_button".

Это мой JS. Я знаю, что это не сработает, я просто не знаю, как это сделать. Я нашел похожие проблемы, но решение всегда кажется сложным для начинающего, как я, чтобы понять. Очень простое решение было бы очень оценено!

  function check_text() { 
       var ui = document.getElementById('ip1').value; 
      } 

      function write() { 
       document.getElementById('ag').innerHTML = ui; 
      } 
+0

Почему бы не использовать только одну кнопку, которая при нажатии вы получаете значение и передать его в пункт, в один присест? –

+0

Я просто хотел знать решение этой точной проблемы, так как хочу понять логику этого. Вы на 100% правильны, используя кнопку 1, это легко разрешит проблему. – sojutyp

ответ

0

Вы должны объявить переменную вне функции: она должна работать

var ui = 0; 
 
function check_text() { 
 
ui = document.getElementById('ip1').value; 
 
} 
 

 
function writeL() { 
 
    document.getElementById('ag').innerHTML = ui; 
 
}
<input type="text" id="ip1" >  
 
      <input type="button" id="check_button" value="checking" onclick="check_text()"> 
 
      <input type="button" id="write_button" value="write" onclick="writeL()"> 
 
    <p id="ag"></p>

+0

Если я объявляю 'var ui = 0;', результат (то, что будет записан в 'ag') равен 0, а не значение, которое вводится в поле ввода. Также я заметил, что я не могу назвать свою функцию write(). Кажется, что write() не является именем функции. – sojutyp

+0

Я добавил рабочий код –

+0

Можете ли вы пометить мой ответ в качестве правильного ответа, просто положите V рядом с ответом –

-1

Вы можете сделать это легко с помощью JQuery, как это:

  var enteredValue = ""; 
 
      $("#check_button").on("click", function() { 
 
       enteredValue = $("#ip1").val(); 
 
      }); 
 
      $("#write_button").on("click", function() { 
 
       $('#store_value').html(enteredValue); 
 
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="ip1" />  
 
     <input type="button" id="check_button" value="checking" /> 
 
     <input type="button" id="write_button" value="write" /> 
 
<p id="store_value"></p>

+0

OP не запрашивал jQuery. Учитывайте это. Проверьте [** это **] (http://needsmorejquery.com/)! –

+0

просто дополнительный ответ – webmaster

+0

Это похоже на простую задачу, которая может быть выполнена с использованием только JS. И OP, похоже, не использует jQuery, поэтому зачем заставить его использовать jQuery. –

0

Есть, конечно, несколько способов обработки вашего значения. В нижеприведенном фрагменте используется HTMLFormControlsCollection. Подробности комментируются в фрагменте. Кстати, я должен был избавиться от одной из кнопок, это, вероятно, помешало бы вашему пониманию, а не помогло бы ему. Лучше визуализировать происходящее, наблюдая за консолью.

SNIPPET

/***NOTE: Any comment having a pencil icon: ✎ 
 
|| means that the expression/statement is there... 
 
||...to show an alternate way. Although they... 
 
||...aren't used in the functions, they can be... 
 
||...used instead of it's counterpart. 
 
*/ 
 

 

 
function processData() { 
 

 
    // Reference the <form> by id or... 
 

 
    var form1 = document.getElementById('form1'); 
 
    // ✎ 
 
    /*1*/ 
 
    console.log('1. This is ' + form1.id + '\n'); 
 

 
    /*...or by HTMLFormControlsCollection... 
 
    ||...reference <form> as the first <form>... 
 
    ||...the .forms is an array-like object... 
 
    ||...the [0] is the index indicating which... 
 
    ||...<form> it's referring to. This is easily... 
 
    ||...determined since there's only one <form>... 
 
    ||...on the page. 
 
    */ 
 

 
    var formA = document.forms[0]; 
 
    /*2*/ 
 
    console.log('2. This is ' + formA.id + '\n'); 
 

 
    // We'll continue using the HTMLFormControlsCollection 
 

 
    /* This is using previously declared formA to... 
 
    ||...reference it's .elements property. The... 
 
    ||...elements property is like the .forms... 
 
    ||...except that it refers to a <form>'s... 
 
    ||...field form elements like <input> and ... 
 
    ||...<output> 
 
    */ 
 

 
    var formUI = formA.elements; 
 
    /*3*/ 
 
    console.log('3. This is an ' + formUI + '\n'); 
 

 
    // We can get the number of form control elements 
 

 
    var qty = formUI.length; 
 
    // ✎ 
 
    /*4*/ 
 
    console.log('4. form1 has ' + qty + ' form control elements\n'); 
 

 
    /* Get the value of text1 by using the object formUI... 
 
    ||...the name of <input>, and the .value property. 
 
    */ 
 

 
    var TXT1 = formUI.text1.value; 
 
    /*5*/ 
 
    console.log('5. The value of text1 is ' + TXT1 + '\n'); 
 

 
    /* We can get the same result by referencing <input>... 
 
    || ...by it's index position in the formUI object... 
 
    || This expression is getting the value of the first... 
 
    ||...form field element of the <form> or formUI object 
 
    */ 
 
    var TXTA = formUI[0].value; 
 
    // ✎ 
 
    /*6*/ 
 
    console.log('6. The value of Text1 is still ' + TXTA + '\n'); 
 

 

 
    /* Return the value of TXT1 
 
    || This function returns a value, so it can be... 
 
    ||...assigned to a var as a value and it can be... 
 
    ||...passed through another function like a... 
 
    ||...parameter. 
 
    */ 
 
    return TXT1; 
 
} 
 

 
/* This will pass a value... 
 
||...reference the <output>... 
 
||...and set <output> value to... 
 
||...given value 
 
*/ 
 
function displayData(value) { 
 
    var output1 = document.getElementById('output1'); 
 
    output1.value = value; 
 
} 
 

 
/* When button1 is clicked... 
 
||...store the return of processData() in a var... 
 
||...then pass that var to displayData() function 
 
*/ 
 
document.getElementById('button1').onclick = function(event) { 
 
    var VAL = processData(); 
 
    displayData(VAL); 
 
}
input { 
 
    font: inherit 
 
}
<form id='form1' name='form1'> 
 
    <input type="text" id="text1" name='text1'> 
 
    <input type="button" value="display" id='button1'> 
 
    <br/> 
 
    <output id="output1" name='output1'></output> 
 
</form>

Смежные вопросы