我在我的 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 »</a> </div>
我的javascript函数
function viewModal(Title1, Story, ID) {
var modal = document.getElementById(ID);
modal.style.display = "block";
}
最佳答案
代码的主要问题是 viewModal
中的 ID
变量。
正如您在这里看到的,您在调用 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 »</a>
关于javascript - 通过 HTML 元素将变量传递给 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884388/