jquery - 传递参数的最佳方式(非常简单的 jquery/html)
问题描述
我使用用户名创建多个按钮
<a id="message-' + onlineUsers[i].username + '"></a>
然后我会用 id 拆分-
来获取用户名?
$('a[id^="message-"]').click(function () {
//I need to get the username here
});
不知何故,这对我来说看起来不正确。正确的做法是什么?
解决方案
你可以像这样使用它:
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello, world!</title>
<style>
</style>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
$(function(){
$('a[id^="message-"]').click(function () {
//I need to get the username here
var thisElem = jQuery(this);
var lastItem = thisElem.attr("id").split("-").pop(-1);
console.log(lastItem); //result "myusername"
});
});
</script>
</head>
<body>
<a id="message-myusername">Click Me</a>
</body>
</html>
推荐阅读
- php - Mysql 存储过程 - 如果未找到数据,则返回表头
- angular - 根据在文本框中输入的值启用/禁用按钮 angular 4 - 初始加载不起作用
- c# - Xamarin Android:如何设置和获取全局变量
- java - java.lang.NoSuchMethodError:org.springframework.beans.support.ResourceEditorRegistrar。
(Lorg/springframework/core/io/ResourceLoader;) - laravel - laravel public/index.php - 哎呀,好像出了点问题
- transactions - 带有事务的 Spring Webflux
- javascript - 不明白这个 javascript 中的闭包示例
- html - 多选多重引导选择2的自动增加和减少高度
- python - Python:单击窗口上的任意位置时如何从按钮上移除焦点
- momentjs - moment-timezone.js 获取具有时区的特定日期的 UTC 偏移量