我确信这很简单,但我似乎无法解决。我正在尝试获取 div 中的文本值。下面的代码来自搜索下拉结果,因此用户将单击搜索结果,然后单击的内容应填充另一个 div。但目前我只想获取 div 中的值“1”或“2”作为变量。
<html>
<head>
<style>
.number:hover{
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#search_result').click(function() {
var txt =
$(this).closest("#search_result").next(".number").find(".number").text();
alert(txt);
});
});
</script>
</head>
<body>
<div id="search_result" style="border-radius: 2px; border:
1px solid rgb(204, 204, 204); z-index: 3; position: absolute; background-
color: white; width: 76.46%; display: block;">
<div class="dropdowncontainer" style="z-index:1000; border-bottom: 1px solid
#E6E6E6; height:20%">
<div class="dropdown" style="height:20%; width:100%; z-index:10">
<div style="height:12px; width:50%; position: float-right">
<img src="1.jpg" style="height:100%; position: float-right" width="60px">
</div>
<div class="number" style="margin-top:-10px; width:100%">
<font color="#2947F2">
<b>1</b>
</font>
</div>
</div>
</div>
<div class="dropdowncontainer" style="z-index:1000; border-bottom: 1px solid
#E6E6E6; height:20%">
<div class="dropdown" style="height:20%; width:100%; z-index:10">
<div style="height:12px; width:50%; position: float-right">
<img src="2.jpg" style="height:100%; position: float-right" width="60px">
</div>
<div class="number" style="margin-top:-10px; width:100%">
<font color="#2947F2">
<b>2</b>
</font>
</div>
</div>
</div>
</div>
</body>
最佳答案
我认为这可能适合您的需求?
我为此使用 $.html()
。
$(document).ready(function() {
$('#search_result .number').click(function() {
var txt =
$(this).find("b").html();
alert(txt);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search_result" style="border-radius: 2px; border:
1px solid rgb(204, 204, 204); z-index: 3; position: absolute; background-
color: white; width: 76.46%; display: block;">
<div class="dropdowncontainer" style="z-index:1000; border-bottom: 1px solid
#E6E6E6; height:20%">
<div class="dropdown" style="height:20%; width:100%; z-index:10">
<div style="height:12px; width:50%; position: float-right">
</div>
<div class="number" style="margin-top:-10px; width:100%">
<font color="#2947F2">
<b>1</b>
</font>
</div>
</div>
</div>
<div class="dropdowncontainer" style="z-index:1000; border-bottom: 1px solid
#E6E6E6; height:20%">
<div class="dropdown" style="height:20%; width:100%; z-index:10">
<div style="height:12px; width:50%; position: float-right">
</div>
<div class="number" style="margin-top:-10px; width:100%">
<font color="#2947F2">
<b>2</b>
</font>
</div>
</div>
</div>
</div>
关于javascript - 如何查找div的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367326/