如何在循环中设置<p>元素的html </p>

时间:2014-12-10 17:33:53

标签: jquery

&#39;我已在JSFiddle中尝试了此操作,但无法使用html更新<p>元素。

有什么理由?

var ts = Math.round((new Date()).getTime() / 1000);
setInterval(function() {
    if (ts>1) {
    alert("done"); // If I include this line I get an alert
    $('p').html('<a href=http://www.getit.com?ts='+ts.val+'"Go</a>');
    ts = Math.round((new Date()).getTime() / 1000);
    }
}, 1000);

4 个答案:

答案 0 :(得分:1)

用双引号括起网址。 (例如,href="your_url"

&#13;
&#13;
var ts = Math.round((new Date()).getTime() / 1000);
    setInterval(function() {
       if (ts > 1) {
           $('p').html('<a href="http://www.getit.com?ts='+ ts +'">Go</a>');
           ts = Math.round((new Date()).getTime() / 1000);
       }
}, 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<p></p>
&#13;
&#13;
&#13;

ts.val也是undefined。它只能是ts而不是ts.val

答案 1 :(得分:1)

http://jsfiddle.net/8wbqsmk8/2/

var ts = Math.round((new Date()).getTime() / 1000);
setInterval(function() {
    if (ts>1) {
    $('p').append('<a href="http://www.getit.com?ts='+ts+'">Go</a>');
    ts = Math.round((new Date()).getTime() / 1000);
    }
}, 1000);

答案 2 :(得分:1)

锚点没有显示,因为它的结果标记不完整,缺少"的开放href>之前的Go:< / p>

<a href=http://www.getit.com?ts=..."Go</a>

<!-- vs. -->
<a href="http://www.getit.com?ts=...">Go</a>

此外,ts中存储的数字不具有.val属性。使用它将始终导致undefined连接而不是时间戳。

console.log(ts);     // 141...
console.log(ts.val); // undefined
<a href="http://www.getit.com?ts=undefined">Go</a>

解决这两个问题应该允许它显示时间间隔更新的ts

$('p').html('<a href="http://www.getit.com?ts='+ts+'">Go</a>');
//                   ^                          ^^   ^

http://jsfiddle.net/9x4skpcL/

答案 3 :(得分:0)

考虑将类应用于p标记。这样做,您可以使用

更改代码
 $('.yourclassname').html... 

但是,您的代码中存在语法错误。

 $('p) instead of $('p')