【问题标题】:Unable to output variables into html无法将变量输出到 html
【发布时间】:2020-09-24 13:00:01
【问题描述】:

当我单击 html 页面上的按钮时,以下脚本会正确打开带有格式化日期的链接。



    $(document).ready(function() {
    $('#button').click(function(e) {  
        var date = /*my script that collects a specific date*/ ;
        var [yyyy, mm, dd] = date.toISOString().split('T')[0].split('-');

        document.getElementById("cid").innerHTML = dd;
        document.getElementById("cim").innerHTML = mm;



             window.open( "https://www.mywebsite.com/" +yyyy );

});

问题:我无法在 html 页面中显示来自变量的数据。 我正在使用此代码:

Date values : <span id="cid"></span> / <span id="cim"></span>

可能是因为脚本仅在我单击#button 时触发?无论如何,我想在单击按钮之前在页面上显示值。 我怎样才能做到这一点 ?谢谢

【问题讨论】:

  • 将逻辑存储在一个函数中,然后在页面加载时调用该函数。你试过吗?
  • 我尝试放入文档准备功能,但它不起作用。我想我是不是在做一个微不足道的 javscript 语法错误?

标签: javascript html variables output getelementbyid


【解决方案1】:

也许我不明白你想要实现什么,但对我来说,当你将逻辑移到点击功能之外时,一切都会很好。

function updateDate(){
  console.log('Updated!')
  const date = new Date();
  const [yyyy, mm, dd] = date.toISOString().split('T')[0].split('-');

  document.getElementById("cid").innerHTML = dd;
  document.getElementById("cim").innerHTML = mm;  
}

$(document).ready(function() {
  updateDate();

  $('#button').click(function(e) {  
    updateDate();
  });
})

看小提琴:https://jsfiddle.net/aofd5vne/1/

【讨论】:

  • 我尝试了您的代码,但它会立即加载目标页面,而不是等待单击按钮。有什么办法可以解决吗?
  • 是的,window.open 在 updateDate 函数之后添加了按钮点击函数。不要在 updateDate 函数中添加打开的窗口
  • 我对 javascript 很陌生,我正在尝试解决自动加载的问题,但目前没有运气。也许你能帮助我?我认为这是一个 javascript 语法问题
猜你喜欢
  • 2019-03-10
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 2022-07-29
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
相关资源
最近更新 更多