简体   繁体   English

jQuery 普通代码 Javascript

[英]jQuery code in plain Javascript

How can I write this jQuery code in plain Javascript?如何在普通的 Javascript 中编写此 jQuery 代码?

I can't use jQuery where this is going to be used.我不能在将要使用它的地方使用 jQuery。

$(function(){
$("td#dark[height='260']").append("<a href='http://www.website.com'></a>");
});

Try this:尝试这个:

var elem = document.getElementById("dark");  // #dark
if (elem && elem.nodeName == "TD" && elem.height == 260) {  // td#dark[height='260']
    var newElem = document.createElement("a");
    newElem.href = "http://www.example.com";
    elem.appendChild(newElem);
}

And for your non-standard document using the same ID on multiple elements:对于在多个元素上使用相同 ID 的非标准文档:

var elems = document.getElementsByTagName("td");
for (var i=0; i<elems.length; i++) {
    var elem = elems[i];
    if (elem.id == "dark" && elem.height == 260) {  // td#dark[height='260']
        var newElem = document.createElement("a");
        newElem.href = "http://www.example.com";
        elem.appendChild(newElem);
    }
}

but the problem is that the site is very non-standard, and uses several ID dark on both td and table tags.但问题是该站点非常不标准,并且在 td 和 table 标记上都使用了几个 ID dark。 Any ideas on how I can make it work?关于如何使它工作的任何想法? – mofle – 莫夫勒

You will need to loop through each HTML element within the body (xpath would be ideal), get the tag, see if its td and if so, read the height element and see if it equals 260. This is because.getElementById will only return one result as only one ID should be present, but as you say, the website is non-standard.您将需要遍历正文中的每个 HTML 元素(xpath 将是理想的),获取标签,查看其 td,如果是,则读取高度元素并查看它是否等于 260。这是因为.getElementById 只会返回一个结果,因为应该只存在一个 ID,但正如您所说,该网站是非标准的。

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

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