问题描述
我正在寻求您的帮助.我想创建一个button
,单击它后将为网站上的所有a
选择器添加下划线样式.我已经写了一个简单的函数,但是不幸的是它不起作用.整个页面上有很多a
选择器,因此我不会发送整个页面的代码.
after an hour of trial and error with the creation of a simple script, I'm asking you for help. I would like to create a button
, which after clicking on it will add an underline style to all a
selectors on the website. I already wrote a simple function, but unfortunately it doesn't work.There is a large number of a
selectors on the whole page, so I won't send out the code of the whole page.
JS文件:
function underlineLinks() {
const links = document.querySelectorAll("a");
links.style.textDecoration = "underline";
}
HTML代码:
<button onclick="underlineLinks()">Underline</button>
functions.php文件中的PHP代码:
PHP code in functions.php file:
function underline_links() {
wp_enqueue_script( 'js-file', get_stylesheet_directory_uri() . '/js/underline.js');
}
add_action('wp_enqueue_scripts', 'underline_links');
推荐答案
并不能真正解释当前问题的原因,但这里已经有足够的内容了.
Not really an explanation to the cause of the issue at hand, yet there are enough of those in here already.
在整个文档或正文中使用css进行操作似乎比分别遍历每个元素更简单.
Doing it with css on the whole document or body seems more simple than looping over each element separately.
window.onload = function(){
document.getElementById('on').onclick = function(){
document.body.classList.add('underline');
};
document.getElementById('off').onclick = function(){
document.body.classList.remove('underline');
}
}
a{text-decoration: none}
body.underline a{text-decoration: underline}
<a>link 1</a>
<a>link 2</a>
<a>link 3</a>
<button id = 'on'>on</button>
<button id = 'off'>off</button>
通常,我会尽量避免使用HTMLElements的style
属性,而是尝试使用类/属性.
In general I would try to avoid using the style
properties of HTMLElements and try to work with classes/attributes instead.
a{text-decoration: none}
body.underline a{text-decoration: underline}
<a>link 1</a>
<a>link 2</a>
<a>link 3</a>
<button onclick = "document.body.classList.toggle('underline')">toggle</button>
这篇关于单击按钮后,如何为网站上的所有链接添加下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!