我想用文本字段中的值更新我的对象。
我认为问题在于按钮上的click eventhandler但不确定。我尝试了一些事情,你的帮助会很棒。
HTML
<form>
<label><p>Book Name: </p></label>
<input name="booktitle" id="booktitle" type="text" value="I'm a value">
<label><p>Total Pages: </p></label>
<input type="text">
<label><p>Current Page: </p></label>
<input type="text">
<button id="my-Btn" type="button">Add to List</button>
</form>
JS
(function() {
// Create book object
var book = {
name: 'JavaScript & jQuery',
totalPages: 622,
pages: 162,
pagesLeft: function() {
var total = this.totalPages - this.pages;
return total;
},
percentageLeft: function() {
var totalPercentage = this.pagesLeft() / this.totalPages * 100
return Math.round(totalPercentage);
}
};
// write out book name and pages info
var bookName, totalPages, pagesLeft, percentageLeft; //declares variables
bookName = document.getElementById('bookName'); // gets elements from document
totalPages = document.getElementById('totalPages');
pagesLeft = document.getElementById('pagesLeft');
percentageLeft = document.getElementById('percentageLeft');
bookName.textContent = book.name; // write to document
totalPages.textContent = 'Total Pages: ' + book.totalPages;
pagesLeft.textContent = book.pagesLeft();
percentageLeft.textContent = book.percentageLeft() + '%';
// pull value from text field and set to object
document.getElementById("my-Btn").addEventListener("click", function() {
book.name = document.getElementById('booktitle').value;
});
}());
目前我所拥有的代码笔。
http://codepen.io/Middi/pen/pRGOVW
提前致谢。
答案 0 :(得分:1)
问题是您在此处book
根据bookName.textContent = book.name;
设置divs textContent:book.name = bookName.value;
bookName.textContent = book.name;
。但是你需要在你的活动中再次这样做:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
int main(){
int fd = open("test.c",O_WRONLY | O_CREAT);
printf("%d\n",fd);
close(fd);
}
您需要为所有字段执行此操作
答案 1 :(得分:1)
您的代码已使用文本字段(book.name
)中的值更新了对象的属性(#booktitle
)。您可以通过在
alert(book.name);
来查看此内容
book.name = document.getElementById('booktitle').value;
正如Jazcash所说,如果您想在每次更改时显示更新的图书名称,您需要添加
bookName.textContent = book.name;
在你的eventlistener中,它看起来像这样:
document.getElementById("my-Btn").addEventListener("click", function() {
book.name = document.getElementById('booktitle').value;
bookName.textContent = book.name;
});