我有一个链接列表,这些链接指向一个页面,该页面对应于美国 50 个州中的每一个。
我循环遍历数组中的每个状态,并为每个状态添加 href,但对于包含两个单词的状态,我需要用连字符 (' '
) 替换它们之间的空格 ('-'
)。
示例:New York
必须替换为 New-York
.
<a href="http://www.projectknow.com/find/New York/" class="spaces">
必须替换为
<a href="http://www.projectknow.com/find/New-York/" class="spaces">
这是我到目前为止得到的,但它不起作用。 jQuery 还是新手,如有任何帮助,我们将不胜感激。
var option = '';
for (var i = 0; i < states.length;i++){
option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
class="spaces">'+ states[i] +'</a></li>';
}
$('.menu').append(option);
$("a.spaces").each(function (){
$(this).attr('href', $(this).attr("href").replace("","-"));
});
最佳答案
改用这段代码:
$(this).attr('href', $(this).attr("href").replace(/\s/g, "-");
关于javascript - 使用 jQuery 我需要用连字符替换 href 内的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44401521/