html - 使用 jquery 选择跨度文本
问题描述
我有这个 html 代码,我想在点击回复时获取跨度文本,但是我的页面中有多个此代码,并且仅选择第一项,这是我的代码
<div class="display-comment" style="margin-right: 10px">
<div class="userProfileImageForComment">
<img src="{{asset('profile-media/'.$comment->user->profileimg)}}" alt="">
</div>
<span id="userName">{{ $comment->user->username }}</span>
<p>{{ $comment->comment }}</p>
<div class="comentActionAndDate">
<span>
{{ jdate($comment->created_at)->ago() }}
</span>
<a id="reply">
reply
</a>
</div>
和脚本是
<script>
$('#reply').click(function(){
var username = "@" + $('#userName').text() + " ";
$('#comment').val('');
$('#comment').val(username);
$('#comment').after( "<input type=\"hidden\" name=\"comment_id\" value=\"{{ $comment->id }}\" />" )
});
</script>
解决方案
var spanText = $(".comentActionAndDate span").html();
我假设这是一个评论线程,在这种情况下,您应该使用相对查找来定位文本。
$('#reply').click(function(){
var spanText = $(this).find(".comentActionAndDate").children("span").html();
// Other stuff you might want to do
});
如果不止一次生成该回复按钮,您也不应该为该回复按钮使用 ID。您还应该使用<button>
非<a>
标签,因为a
标签用于链接。
最正确的方法是使用onclick
回复按钮的功能:
<button onclick="getSpan(this);">reply</button>
JS:
function getSpan(ele) {
var spanText = $(ele).find(".comentActionAndDate").children("span").html();
// Other stuff you might want to do
}
推荐阅读
- reactjs - 你如何在 reactjs/material-ui 的 GRID 中更改(使其变大)图标的大小?
- php - 将 HTML/Bootstrap 列表转换为在 PHP 中返回值的列表
- c# - 在从 Entity Framework 检索对象列表时可以忽略对象的 OnPropertyChanged 吗?
- java - 在带有通配符的通用列表中使用值
- python - 处理方法中的异常
- html - 关于响应式布局和不显示某些元素
- terraform - 如果 VM 是从平台、用户或共享库映像创建的,则无法附加现有 OS 磁盘
- html - 如何使列自动调整大小?
- sql - 计算单词 y sq 和 posgresql
- networking - 将网站设置为 Internet 流量,无法转发端口或对 raspberryPi 使用本地 ssh