繁体   English   中英

如何使用JavaScript查找带有img标签的单元格?

[英]How to find cells with img tag using JavaScript?

我正在寻找一种仅使用img标签从表中选择单元格并仅使用JS更改样式的方法。

<table border="1" id="table1">
<tr>
<td id="0"><img src="background.jpg"></td><td id="1"></td><td id="2"></td><td id="3"></td>
</tr>
</table>

我想在表单中使用它,但是我不知道如何使它起作用。 我尝试了此操作(在其中,我想通过在表单中​​输入的ID查找img,但我知道-它不起作用)

 function form1() {
    var x = document.getElementsByTagName("img");  
    var y = document.getElementById('formu').value;
 if (x=y) {

    console.log(x)

}




<form>
    <fieldset>
        <label for="ship"></label>
        <input type="text" id="formu" name="ship" value="" />
    </fieldset>

    <input type="button" onclick="check()" value="fire!">
</form>

如果以这种形式,我将id单元格放在存在标签img的位置,我想更改该单元格的样式。

在javascript中,您可以选择如下图像:

var tdImages = document.querySelectorAll('td > img');

然后遍历它们并使用parentNode

var td, index = 0, length = tdImages.length;
for ( ; index < length; index++) {
    td = tdImages[index].parentNode;
}

这是一个小提琴示例: http : //jsfiddle.net/y1vseo5t/

编辑:因此,您想让用户在输入中输入一个ID,然后从中确定该表数据元素是否具有图像,如果它确实改变了其样式。

http://jsfiddle.net/y1vseo5t/1/

选择器不能以数字开头,因此我将表数据元素上的ID更改为td0,td1 ...

如果您必须坚持使用数字作为ID中的第一个字符,这是另一种解决方案: http : //jsfiddle.net/y1vseo5t/2/

最好在jQuery中完成,您可以在其中使用has选择器

$("td").has("img").each(function() {
});

这是JavaScript解决方案

var cellsWithImage = document.querySelectorAll("td > img");

for (var i = 0; i < cellsWithImage.length; i++) {
    cellsWithImage[i] = cellsWithImage[i].parentNode;
}

请注意,我们必须使用循环,因为数组方法filtermap不适用于DOM集合。

关于您的代码,我还有另一条说明。 您正在使用document.getElementsByTagName函数,但是该函数返回的集合不是DOM对象。 您需要将对象的索引放在括号内以引用特定的图像。

document.getElementsByTagName("img")[0]       // Returns first image

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM