我正在尝试使用.html()
获取范围的内容。它适用于没有内部标签的span。但在其他情况下,所有标签都会出现。我只需要内容。
我添加了一个片段,
$(function(){
$("#MainButton").click(function(){
var mainSpan = $("#MainSpan").html();
alert(mainSpan);
})
$("#InnerButton1").click(function(){
var innerSpan1 = $("#InnerSpan1").html();
alert(innerSpan1);
})
$("#InnerButton2").click(function(){
var innerSpan2 = $("#InnerSpan2").html();
alert(innerSpan2);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="MainSpan" style="display:none">
MainSpan
<span id="InnerSpan1">
InnerSpan1
</span>
<span id="InnerSpan2">
InnerSpan2
</span>
</span>
<button id="MainButton">Alert Main</button>
<button id="InnerButton1">Alert Inner 1</button>
<button id="InnerButton2">Alert Inner 2</button>
我想要的是,单击按钮Alert Main
时需要类似
MainSpan InnerSpan1 InnerSpan2
我怎么得到这个?
答案 0 :(得分:2)
如果只需要文本,请改用.text()
:
var mainSpan = $("#MainSpan").text();
$(function(){
$("#MainButton").click(function(){
var mainSpan = $("#MainSpan").text();
alert(mainSpan);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="MainSpan" style="display:none">
MainSpan
<span id="InnerSpan1">
InnerSpan1
</span>
<span id="InnerSpan2">
InnerSpan2
</span>
</span>
<button id="MainButton">Alert Main</button>
<button id="InnerButton1">Alert Inner 1</button>
<button id="InnerButton2">Alert Inner 2</button>
如果希望将它们全部放在一行上,则可以使用正则表达式将所有空格替换为一个空格:
$(function(){
$("#MainButton").click(function(){
var mainSpan = $("#MainSpan").text().replace(/\s{2,}/g, ' ').trim();
console.log(mainSpan);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="MainSpan" style="display:none">
MainSpan
<span id="InnerSpan1">
InnerSpan1
</span>
<span id="InnerSpan2">
InnerSpan2
</span>
</span>
<button id="MainButton">Alert Main</button>
<button id="InnerButton1">Alert Inner 1</button>
<button id="InnerButton2">Alert Inner 2</button>