我正在尝试用 JavaScript 编写一个简单的脚本,仅用于测试目的。我正在定义 2 个变量,有点不必要,但无论如何它们都保存两种不同场景的字符串值,如果单击按钮时按钮之前的元素包含粗体文本,则相应的变量将显示在警告对话框中。
所以,这是我的代码:
$(document).ready(function(){
var Bold="Yes, some of this text is bold!";
var NoBold="No, none of this text is bold.";
$("<input class="BoldButton" type="button" value="Bold?" id="IntroButton"></input>")
.insertAfter("#intro");
$("<input class="BoldButton" type="button" value="Bold?" id="LatestNewsButton"></input>")
.insertAfter("#news h2");
$("input.BoldButton").click(function(){
if () {
$('').();
} else {
$('').();
{
});
});
当我意识到我不知道如何检查按钮上方的元素中是否为粗体时,我正在编写 if else 语句。我正在考虑使用伪变量 this,但我很确定这是错误的,因为它不会是“this”伪变量之前的元素吗?我想我可能混淆了这样做的目的,对此感到抱歉。
无论如何,我真的只需要一种方法来检查按钮之前的元素是否包含粗体文本,然后我就可以做剩下的事情了。 :)
谢谢!
最终代码:
$(document).ready(function(){
var Bold="Yes, some of this text is bold!";
var NoBold="No, none of this text is bold.";
$('<input class="BoldButton" type="button" value="Bold?" id="IntroButton">')
.insertAfter("#intro");
$('<input class="BoldButton" type="button" value="Bold?" id="LatestNewsButton">')
.insertAfter("#news p");
$("input.BoldButton").click(function(){
if ($(this).prev().is(':has(b, strong)')) {
alert(Bold);
} else {
alert(NoBold);
}
});
});
最佳答案
如果文本使用 <b>
加粗标签,你可以使用 .is()
方法与 :has()
前一个元素上的选择器以检查它是否有任何后代 <b>
标签。
像这样:
$("input.BoldButton").click(function(){
if ($(this).prev().is(':has(b,strong)')) {
// do something
} else {
// do something else
}
});
.is()
如果匹配提供的选择器,则返回一个 bool 值。 :has()
选择器确定是否存在提供了选择器的后代。
编辑:根据评论中的要求,已更新以包含对 <strong>
的检查标签也是如此。
关于javascript - 替代 "this"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3363609/