我的Java脚本(jQuery)有点生疏,但我正在尝试在网页上添加功能。该脚本将逐步执行,但是该值不会在页面上更新。我可能会忘记一些小东西,但在寻找它时却找不到。
我的网页上生成了以下html
<div class="panel-body">
Great job on this vintage piece of machinery!
<br />
<span id="thumbs">
<a href="javascript:void(0)" data-vote="up" data-id=1 value="up">👍</a>
<a href="javascript:void(0)" data-vote="down" data-id=1 value="down">👎</a>
</span>
<span class="likedisplay">
Likes <span id="upvotes"><strong>27</strong></span>
DisLikes <span id="downvotes"><strong>6</strong></span>
</span>
</div>
这是脚本。
$("#thumbs a").on("click", function (e) {
e.preventDefault();
var commentId = $(this).data("id");
var vote = $(this).data("vote");
increment(vote, commentId);
});
function increment(vote, commentId) {
if (vote === "up") {
//call the database to increase the like count for this comment
//IncrementLikes(commentId);
$("#upvotes").val(parseInt($("#upvotes").val()) + 1);
toastr.info("Your Like was posted!");
}
if (vote === "down") {
//call the database to increase the like count for this comment
// IncrementDisLikes(commentId);
$("#downvotes").val(parseInt($("#downvotes").val()) + 1);
toastr.info("Your DisLike was posted!");
}
}
$(“#upvotes”)。val可以逐步执行,但不会更新页面上的值。我想念什么?
最佳答案
1.因为要处理text()
,所以需要val()
而不是span
。 val()
应用于input fields
。
2.需要$("#upvotes strong")
代替那里的$("#upvotes")
(也与downvotes
相同)。
3. data-id="1"
是正确的方式,而不是data-id=1
工作代码:
$("#thumbs a").on("click", function (e) {
e.preventDefault();
var commentId = $(this).data("id");
var vote = $(this).data("vote");
increment(vote, commentId);
});
function increment(vote, commentId) {
if (vote === "up") {
$("#upvotes strong").text(parseInt($("#upvotes strong").text()) + 1);
toastr.info("Your Like was posted!");
}
if (vote === "down") {
$("#downvotes strong").text(parseInt($("#downvotes strong").text()) + 1);
toastr.info("Your DisLike was posted!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body">
Great job on this vintage piece of machinery!
<br />
<span id="thumbs">
<a href="javascript:void(0)" data-vote="up" data-id="1" value="up">👍</a>
<a href="javascript:void(0)" data-vote="down" data-id="1" value="down">👎</a>
</span>
<span class="likedisplay">
Likes <span id="upvotes"><strong>27</strong></span>
DisLikes <span id="downvotes"><strong>6</strong></span>
</span>
</div>