在我的页面上,我有一个搜索表单,它会生成结果表。在该表中,每个单元格内容都被一个 span 标记包围,该标记的 ID 基于数据库中的单元格名称和行 ID。此外,跨度有一个固定的类别。这是一个打印示例:
<td><span id="firstname_203" class="text">John</span></td>
我想做的是,当我将鼠标悬停在包含名字的单元格上时,我希望名字出现在页面的不同部分。我尝试了下面的代码,但它只返回firstname=null:
( function($) {
$(document).ready(function()
{
$(".text").hover(function()
{
var ID=$(this).attr('id');
var firstname=$("#firstname_"+ID).html();
$($(".firstname")).html("firstname="+firstname);
});
});
} ) ( jQuery );
这是 ID 部分不起作用,因为如果我对 ID 进行硬编码(例如“#firstname_203”),它就可以正常工作。
当我思考这个问题时,我唯一需要知道的是如何获取ID后面的php生成的整数。
更新:
添加更多变量时 (this).text 不起作用,因为它返回了整行值。相反,我不得不使用这个:
$("#table td:nth-child(1)").hover(function(event){
并将单元格返回为:
var firstname= $td.eq(0).text();
等等。
最佳答案
您可以跳过整个 Id 困惑,直接进入 .html()
。
(function($) {
$(document).ready(function() {
$(".text").hover(function() {
var firstname = $(this).html();
$(".firstname").html("firstname=" + firstname);
});
});
})(jQuery);
此外,您可能可以使用 .text()
来逃脱惩罚。
编辑:
给定这个 html
<div class="userDetails">
<span class="fname">Barry</span>
<span class="lname">Smith</span>
</div>
<div class="firstname">Firstname</div>
<div class="lastname">Lastname</div>
你可以这样做:
(function($) {
$(document).ready(function() {
$(".userDetails").hover(function() {
var firstName = $('.fname', this).text();
var lastName = $('.lname', this).text();
$(".firstname").html("firstname=" + firstName);
$(".lastname").html("lastname=" + lastName);
});
});
})(jQuery);
我已经为你创建了一个 jsFiddle - http://jsfiddle.net/HZRSW/
关于jquery - 使用 JQuery 获取带有变量 id 的 php 创建的 div 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671157/