我正在尝试将这几行基于jQuery的代码转换为vanilla JS,但我正在努力。有人可以解释一下怎么做吗?
function googletranslate() {
$(".footer-toggle li, .select-lng li").on("click", function() {
var rel = $(this).children("a").attr("rel");
$(".goog-te-menu-frame:first").contents().find(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')").get(0).click();
});
}
setTimeout(googletranslate, 1000);
我知道如何使用javascript进行点击事件,但我很难找到元素(刚刚开始学习)。
<a href="#" rel="Spanish" title="Spanish">Spanish</a>
基本上,当点击链接时,它会通过rel值将隐藏的谷歌翻译小部件输入,并模拟所需语言的点击。
有人可以解释一下吗?是否更容易使用选择框并从中获取值?
答案 0 :(得分:1)
/* ======= Server start ==============================================*/
package main
import (
"fmt"
"net"
"os"
)
func processClients(cfd net.Conn) {
clientMsg := make([]byte, 128)
_, err := cfd.Read(clientMsg) // read client msg
if err != nil {
return
}
clientID := make([]byte, 10)
_, err = cfd.Read(clientID) // read client id
if err != nil {
return
}
clientMsg = append(clientMsg, clientID...) // TBD: handle len boundaries
fmt.Println("Server received msg:", string(clientMsg))
_, err = cfd.Write(clientMsg[0:len(clientMsg)]) // ack client msg
if err != nil {
return
}
}
func initServer() {
lfd, err := net.Listen("unix", "/tmp/unix.socket")
if err != nil {
fmt.Println("net.Listen error", err)
return
}
defer os.Remove("/tmp/unix.socket")
fmt.Println("Listening on /tmp/unix.socket")
for {
fd, err := lfd.Accept()
if err != nil {
fmt.Println("Accept() error", fd)
break
}
go processClients(fd)
}
}
func main() {
initServer()
}
/* ======= Server end ===============================================*/
/* ======= Client Start ===============================================*/
package main
import (
"fmt"
"net"
"sync"
)
var wg sync.WaitGroup
var clientID int
func sendReq() {
fd, err := net.Dial("unix", "/tmp/unix.socket")
if err != nil {
return
}
defer fd.Close()
clientID++
id := fmt.Sprintf("%v", clientID)
_, err = fd.Write([]byte(id)) //send client id
if err != nil {
return
}
_, err = fd.Write([]byte("Hello there, I am client")) // send client msg
if err != nil {
return
}
serverMsg := make([]byte, 128)
_, err = fd.Read(serverMsg) // Read server msg
if err != nil {
return
}
fmt.Println(string(serverMsg))
wg.Done()
}
func main() {
wg.Add(5)
go sendReq()
go sendReq()
go sendReq()
go sendReq()
go sendReq()
wg.Wait()
}
/* ======= Client end ===============================================*/
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
答案 1 :(得分:0)
function googletranslate() {
['.footer-toggle li', '.select-lng li'].forEach(selector => {
const elm = document.querySelector(selector);
elm.addEventListener('click', clickHandler);
});
function clickHandler(e) {
const rel = e.target.querySelector('a').getAttribute('rel');
const someGoogleSpan = document.querySelector(".goog-te-menu-frame:first")
.querySelectorAll(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')")[0];
someGoogleSpan.click();
}
}
setTimeout(googletranslate, 1000);