基本上,我正在创建一个upvote / downvote系统,现在我已经在HTML中创建了两个按钮:
<button type="button" name="upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="downvote"></button>
第一个具有名称属性的按钮-“ upvote”,第二个具有“ downvote”,现在我想单击一个按钮并相应地更改 commentValue ,如果用户单击upvote,则进行注释值必须增加,投票时必须减少
我发现一些主题据说可以实现ActionListener,Create JButton对象等,但是没有任何更简单的方法吗?
这是我现在的代码,按钮什么也不做。 :
控制器:
private int numberValue = 0;
@GetMapping("/check")
public String nuberCheck(Model model){
model.addAttribute("commentValue", numberValue);
return "numberCheck";
}
@PostMapping("/check")
public String upvote(Model model, @RequestParam String action){
if (action == "upvote"){
numberValue++;
model.addAttribute("commentValue", numberValue);
}else if (action == "downvote"){
numberValue --;
model.addAttribute("commentValue", numberValue);
}
return "numberCheck";
}
numberCheck:
<form action="#" th:action="@{/check}" method="post">
<button type="button" name="action" th:value="upvote" th:text = "upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="action" th:value = "dowvnote" th:text = "dowvnote"></button>
</form>
已修复
将按钮类型更改为“提交”,然后在控制器中:
@PostMapping("/check")
public String check(Model model,@RequestParam String action) {
System.out.println(action);
if (action.equals("upvote")) {
numberValue++;
model.addAttribute("numberValue", numberValue);
}
if (action.equals("dowvnote")) {
numberValue--;
model.addAttribute("numberValue", numberValue);
}
return "numberCheck";
}
@RequestParam String action
“操作”是按钮的名称属性,“保存”和“取消”是“值”属性:)希望对您有所帮助
答案 0 :(得分:0)
使用以下内容并在您的代码中实现
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
答案 1 :(得分:0)
示例:
HTML:
<form action="#" data-th-action="@{/action}" data-th-object="${model}" method="post">
<button type="submit" name="upvote"></button>
<button type="submit" name="downvote"></button>
</form>
Java:
@RequestMapping(value="/action", method=RequestMethod.POST)
public ModelAndView onClickAction() {}
答案 2 :(得分:0)
您可以为此使用jquery。首先在您的html页面中添加jquery库,并在script
标记内编写如下函数
function upVote(){
var counter= $('.comment').val();
counter++;
$('.coment').val(counter);
}
function downVote(){
var counter= $('.comment').val();
counter--;
$('.coment').val(counter);
}
<button type="submit" name="upvote" th:onclick="'upVote();'"></button>
<br>
<input type="number" class="comment"th:value = "${commentValue}" disabled>
<br>
<button type="submit" name="downvote" th:onclick="'upVote();'"></button>
答案 3 :(得分:0)
有一种最好的解决方法。单击按钮触发一个事件,然后在该事件上增大或减小值。在百里香叶中使用该值并将其传递给控制器。