javascript - 在 div 中获取一个 span innerHTML

标签 javascript html css timer innerhtml

您好,我已经四处寻找几天了,但我真的找不到任何东西,我想要的是在 div 中调用一个 span 并获取 span innerHTML。 现在代码如下所示:

跨度如下所示:

function createTimer() {
        return document.createElement("span");
    }

如您所见,此跨度位于此 div 内部:

var Stopwatch = {
init: function(elem, options) {

    var timer = createTimer(),
    startButton = createButton("start", start),
    stopButton = createButton("stop", stop),
    resetButton = createButton("reset", reset),
    offset,
    clock,
    interval;

    options = options || {};
    options.delay = options.delay || 1;

    elem.appendChild(timer);
    elem.appendChild(startButton);
    elem.appendChild(stopButton);
    elem.appendChild(resetButton);

    reset();

    function createTimer() {
        return document.createElement("span");
    }

我尝试使用 Stopwatch.span.innerHTML 调用它, .stopwatch span.innerHTML以及许多其他不同的方式。您可以使用此 .stopwatch span 在 css 中调用它但这是我需要在按钮或类似的东西中调用它的问题 <button id="first" onclick=".stopwatch span.innerHTML;"></button> . 但它确实有效!如果有任何问题,请提前致谢! :)

更新:这是一个凌乱的 JsFiddle http://jsfiddle.net/dzcv9847/

最佳答案

您必须深入研究该函数并将 var timer = createTimer(), 更改为 this.timer = createTimer(); 才能使用类似 Stopwatch.timer.innerHTML; 无论现在创建计时器的方式如何,都无法按原样访问该对象。

这无需更改即可工作:

window.onload=function() {
  var elems = document.getElementsByClassName("basic");
  for (var i = 0, len = elems.length; i < len; i++) {
    Stopwatch.init(elems[i]);
  }
  document.getElementById("first").onclick=function() {
    var val = document.querySelector('.stopwatch > span').innerHTML;
    document.getElementById("lap").innerHTML=val;
  }  
}

FIDDLE


更新:更优雅一点:

    lapButton = createButton("lap", lap),
    lapSpan = createTimer(),
    ...
    function lap() {
      lapSpan.innerHTML=timer.innerHTML;
    }

    function reset() {
        clock = 0;
        render(0);
        lap();
    }

FIDDLE

关于javascript - 在 div 中获取一个 span innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28780114/

相关文章:

javascript - 表单仅提交一个值,在同一页面中使用 AJAX 将表单数据传递给 PHP

html - 将原始 HTML 代码转换为 PDF 文件

javascript - 如何在 <a> 标签中调用 onclick 函数?

javascript - 使用jQuery animate向左滑动时保留css float

html - 将 h1 对齐到 float 图像的右侧

javascript - div 背景轻松,悬停时透明覆盖

javascript - 将选中的表行添加到电子邮件正文

php - 实时保存的表单。实际的?

javascript - 返回深度嵌套数组中对象索引的函数

html - 滑动 View 中幻灯片的 CSS