[英]Adding text to a dynamically created DOM element
I'm trying to create <div>
elements with child <p>
elements; 我正在尝试使用子<p>
元素创建<div>
<p>
元素; the <div>
elements are being assigned a class of "clock" + a number (increments). <div>
元素被分配了一个“时钟” +一个数字(递增)的类。 While the elements themselves seem to be created, adding text (in my case a moment object) to the <p>
element doesn't work. 尽管元素本身似乎是创建的,但无法向<p>
元素添加文本(在我的情况下为矩对象)。
HTML: HTML:
<body>
<select class="tz_list" name="timezones">
<option value="default">Please Select a Timezone</option>
</select>
<input type="button" name="addClock" value="Add Clock" class="button">
</body>
JS: JS:
$(document).ready(function () {
var now = moment();
console.log(now);
//var repeat = setInterval(displayTime, 200);
var tzones = moment.tz.names();
tzones.forEach(function(key,value){
$('<option/>').val(key).html(key).appendTo('.tz_list');
});
var repeat;
var clock_count = 1;
var timezone ="";
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock '+clock_number.toString() + ' p';
console.log(selector);
//$('.clock '+clock_number.toString()).css({"height":"100px", "width":"500px"});
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock '+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
$('.tz_list').on('change', function(event){
console.log(event.target.value);
timezone = event.target.value;
});
});
Instead creating class "clock " try to create with out giving space. 而是创建类“ clock”,尝试在没有空间的情况下进行创建。 It will work. 它会工作。
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock'+clock_number.toString() + ' p';
console.log(selector);
//$('.clock'+clock_number.toString()).css({"height":"100px", "width":"500px"});
$('.clock'+clock_number.toString()).text(timezone);
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock'+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
Change this line: 更改此行:
$('.clock.'+clock_number.toString()).text(timezone);
add the "." 添加“。” after clock but is not a god practice add number as class, instead use something like clock_1 (or clock1 like the answer below) 在时钟之后,但不是神练习将数字添加为类,而是使用诸如clock_1(或诸如下面的答案的clock1)之类的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.