【发布时间】:2012-01-23 20:23:12
【问题描述】:
我试图找到一个包含图像的节点,然后在该图像的标签中找到一个特定的字符串。但我不知道图像标签何时会出现在页面上,除了它只出现在被归类为bodyTextSmall 的td 元素中。那应该能让我到达那里,对吧?
一切正常,直到我尝试获取childNodes 属性的length。见上一行。
这是正确的代码,还是有另一种方法可以找出特定的 td 是否在其中某处有 img 标记?我正在撕掉我剩下的一点头发,因为根据我对 JavaScript 的了解,它应该是这样工作的。
问题是我只通过img标签知道我是否需要格式化td标签,我没有组装td标签,无法进入网站的那部分直接进行更改。我已经尝试过 CSS 选择器来查看是否可以设置部分图像的样式,但是有些内联样式我无法覆盖。同样,这是我无法控制的网站的一部分。
<script type="text/javascript">
function getTables(dRef) {
var d = document;
var dMid = d.getElementById('mainContent');
var dTabs = dMid.getElementsByTagName('td');
// Attempts to load table cells...
for (var i = 0; i < dTabs.length; i++) {
// Attempts to detect the specific cell type...
if (dTabs[i].className == "bodyTextSmall") {
// Attempts to locate the parts inside this cell...
var myNodes = i.ChildNodes; // This part runs, but I can't get "ChildNodes.length" to work
// Attempts to notify the user...
alert(dTabs[i].className + ': ' + i);
}
}
}
window.onload = getTables;
</script>
所以,现在我已经切换到 jQuery,我遇到了同样的问题。我可以分辨出图像在哪里,但我无法对图像本身做任何事情。
<script type="text/javascript">
function getTables() {
// Locates the correct container for images...
$('#mainContent img').each(function(idx, item) {
var tImgs = item.src;
if (tImgs.indexOf("-ds.") > 0) {
window.alert(tImgs);
$(this).append('Here is a message about the image.'); //nothing happens here
}
});
}
window.onload = getTables;
</script>
同样,此 jQuery 代码通过响应任何具有“-ds”的图像来响应。 src 中的任何位置。我不能让其他任何事情发生。我知道 $(img).append 会影响每张图片,所以脚本可以做一些事情。
现在这已经变成了得到比我想要的更多或什么都没有的情况,这真的开始让我感到最后的神经了。
【问题讨论】:
标签: javascript html jquery dom html-table