gpt4 book ai didi

javascript - 如何使用 JQuery 更改 EJS 中的单个元素

转载 作者:行者123 更新时间:2023-12-02 22:14:30 25 4
gpt4 key购买 nike

所以我现在遇到了问题。在我的代码中,我在向用户显示代码时会遍历一个数组。但是,当我想使用 JQuery 选择一个元素来使用 .val 方法进行更改时,它会更改具有该类名称的所有元素吗?我是 Node 和 JQuery 的新手,所以请指出任何重复项。如何才能使单击元素时仅该元素发生变化?

JQuery 代码:

$('.likebutton').on('click', function(){ // hit like
console.log("like clicked?"); // works
// i need to find a way to connect this with code and make it update???

var curr = $('#changeit').val();
var item = $('.likebutton').val('Liked'); // problem
console.log("item: " + curr);
$.ajax({ //do something with the data via front-end framework, so we can update in reall time
type: 'GET',
url: '/',
success: function(err){
// here we will get the data, find it in the data base and update it. Changes will occur
// via a reload, either manually or when they create a post, for now. Later we can update
// the thing in real time.

// on click we must also change the color of the thing too to show that it was liked
console.log('success!');
}
});
return false;

});

EJS代码

<!DOCTYPE html>
<html>
<head>
</head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="/assets/chat.js"></script>
<body>
<h1> Ut whispers</h1>
<form action="/" method="POST">
<input type="text" placeholder = "say something" name="msg"> <input type="submit" value="Submit"> <br>
</form>
<ul>
<% for(var i = 0; i < chats.length; i++) { %>
<li class = "display"><%= chats[i].msg %> <input type="button" id = "changeit" class = "likebutton" value = "Like: (<%=chats[i].likes%>)" >
<ul>
<li>replies will go here</li>
</ul>
</li>
<% } %>
</ul>
</body>
</html>

最佳答案

使用关键字“this

"In many ... programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked. "

您需要引用被单击的对象,可以使用“this”来实现。

因此,在您的代码中,更改:

var item = $('.likebutton').val('Liked'); // problem

对此:

var item = $(this).val('Liked'); // problem

当我这样思考时,我发现更容易记住关键字:

我想要将事件附加到的这个东西(按钮、输入、链接或其他任何东西)来执行任务。

详细了解“this”关键字 here .

<小时/>

回复您的评论。在 for 循环中,您使用的是 ID。这不是一个好主意,因为 ID 不是唯一的,因此您应该删除 for 循环中对 ID 的任何引用。

您总是获得第一个值的原因是因为查询选择器找到具有 ID (#changeit) 的第一个元素并使用该元素的值。

您应该再次使用“this”关键字来获取该值,因为您尝试获取的值存储在您单击的按钮中。

因此,在您的代码中,更改:

var curr = $('#changeit').val();

对此:

var curr = $(this).val();

关于javascript - 如何使用 JQuery 更改 EJS 中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59432915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com