如果“if”语句匹配,如何将图像追加到表中

How to append an image into a table if the `if` statement matches?

本文关键字:图像 追加 if 语句 如果      更新时间:2023-09-26

我不知道这是否可能,但在下面我有一个简单的html表格:

<table id="plus" align="center">
  <tr>
    <th>
    </th>
  </tr>
</table>

如果 if 语句匹配,那么是否可以将图像附加到上面的 <th> 标记中?如果语句不匹配,那么我可以改为将图像链接附加到 <th> 标签中吗?

下面是if语句,它实际上是jQuery,它包含了一些php来尝试找到"textQuestion":

if (qnum == <?php echo (int)$_SESSION['textQuestion']; ?>) {
  <img src="Images/plussigndisabled.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" name="plusbuttonrow"/>
} else {
  <a onclick="return plusbutton();">
  <img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" name="plusbuttonrow"/>
  </a>
}

既然你说你正在使用jQuery,你可以这样做

....
    var enabledImage = "plussign.jpg";
    var disabledImage = "plussigndisabled.jpg";
    var selectedImage;
    var imageHtml;
    if(...) {
        selectedImage = enabledImage;
    } else {
        selectedImage = disabledImage;
    }  
    imageHtml = getImageHtml(selectedImage);
    $('#ElementID').append($(imageHtml));
....
function getImageHtml(imageFileName) {
    return '<img src="Images/' + imageFileName + '" width="30" height="30" alt="Look Up Previous Question" class="plusimage" name="plusbuttonrow"/>';
}

将唯一 ID 应用于 TH,如下所示:

<table id="plus" align="center">
  <tr>
    <th id="foo">
    </th>
  </tr>
</table>

然后只使用内部 HTML 属性。

var bar=document.getElementByID('foo');
bar.innerHtml="<img />";

(这假设javascript是响应用户输入而运行的,即在页面加载完成后)

无论哪种方式,您都将附加某些内容,因此请确定要附加的内容 if-statement ,然后附加它。无论哪种方式,它都在同一个地方。

$("#plus th").html(function(){
    return ( qnum === 5 )
        ? "<img />"
        : "<a><img /></a>" ;
});

此时,附加data

工作演示 http://jsfiddle.net/26Jaf/

好的 API:http://api.jquery.com/append/

法典

var qnum = 1;  
var append_data = "";
if (qnum == 1) { // i.e. if condition satisfy.
   append_data = '<img src="http://images.wikia.com/maditsmadfunny/images/5/54/Hulk-from-the-movie.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" name="plusbuttonrow"/>';

} else {
   //do something else
alert('d');
}
$("#plus tr th").append(append_data);
​