通过HTML元素将变量传递给javascript

时间:2018-02-20 11:33:43

标签: javascript jquery html modal-dialog

我的HTML中有3个隐藏按钮,我创建它们来保存我的值。

第四个提交按钮将获取这3个按钮的值,并将它们用作Javascript函数的参数。

我的隐藏按钮

<button type="button" value="Title Retrieved should be here" id="TitleHolder" style="visibility: hidden;"></button>
<button type="button" value="Each year, thousands of patients and families from across the United States and beyond travel to Boston Children's Hospital to seek treatment for complex diseases and conditions. All of our patients are unique, but their stories tend to have a lot in common: a serious health problem, doctors and nurses collaborating from half a world away, the remarkable determination of children and families -- and a happy ending." id="StoryHolder" style="visibility: hidden;"></button>
<button type="button" value="25" id="IDHolder" style="visibility: hidden;"></button>

要点击的按钮并发送值

<a id="btn" class="initialism basic_open" onclick="viewModal(document.getElementById('TitleHolder').value, document.getElementById('StoryHolder').value, document.getElementById('IDHolder').value)" >Read full story &raquo</a> </div>    

我的javascript功能

function viewModal(Title1, Story, ID) {
    var modal = document.getElementById(ID);

    modal.style.display = "block";
}

1 个答案:

答案 0 :(得分:1)

您的代码的主要问题是ID中的viewModal变量。 正如您在此处看到的那样,当您致电viewModal时,您从未通过模态ID

viewModal(document.getElementById('TitleHolder').value, document.getElementById('StoryHolder').value, document.getElementById('IDHolder').value)

我更改了您的代码,使其“更清洁”。这是你想要的工作版本。避免将事件直接添加到HTML元素上。

//Wait till the page has finished loading.
window.addEventListener("load", function(){
  
  //Retrieve and store the hidden inputs elements.
  var storyHolder = document.getElementById('StoryHolder');
  var idHolder = document.getElementById('IDHolder');
  var titleHolder = document.getElementById('TitleHolder');

  //Add click event on button.
  document.getElementById('btn').addEventListener('click', function(){
      //When button is clicked, log all the hidden input values.
      console.log(storyHolder.value, idHolder.value, titleHolder.value);

     //TODO: Modal code here.
     //UNCOMMENT: document.getElementById('REPLACE_THIS_WITH_MODAL_ID').style.display = "block";
  });
});
<input type="hidden" value="Title Retrieved should be here" id="TitleHolder"/>
<input type="hidden" value="Each year, thousands of patients and families from across the United States and beyond travel to Boston Children's Hospital to seek treatment for complex diseases and conditions. All of our patients are unique, but their stories tend to have a lot in common: a serious health problem, doctors and nurses collaborating from half a world away, the remarkable determination of children and families -- and a happy ending." id="StoryHolder"/>
<input type="hidden" value="25" id="IDHolder">

<a id="btn">Read full story &raquo</a>