无法获取childnodes.length
我试图找到一个包含图像的节点,然后在该图像的标记中找到特定的字符串。但我不知道在页面上何时会出现图像标签,除了它仅出现在分类为bodyTextSmall
的td
元素中。这应该让我在那里,对吧?无法获取childnodes.length
一切正常,直到我试图获得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会影响每个图片,所以脚本可以做某些事情。
这现在已经成为一种比我想要的还要多的东西,而且它真的开始让我最后的神经感到厌倦。
i.ChildNodes
未定义。
您的意思是childNodes
。
此外,i
是一个数字,而不是DOM元素。
您的意思是dTabs[i]
。
var myNodes = dTabs[i].ChildNodes;
function dFixIt() {
$('#mainContent img').each(function(idx, item) {
var tImgs = item.src;
if (tImgs.indexOf("-ds.") > 0) {
$(this).parent().after('Here is a message about the image');
}
});
}
这此将定位任何与ID“搜索Maincontent”的元素内,如果它是一个图像。然后它将确定字符串“-ds”。在图像名称中的任何地方。所以“my-friends-ds.jpg”会添加一些东西。
如果图像位于链接内,“.parent()”会在添加消息之前将脚本跳转到该链接之外。这可以防止添加的内容成为链接。
如果图像不在链接内,请从字符串中删除“.parent()”,并且应该在图像后面直接添加消息。
+1我错过了 – SLaks 2011-12-19 18:53:00