我需要将 span 内的文本传递(使用 javascript)到 href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
例如,当我点击关于链接必须是 example.com/tag/about/
我需要将 span 内的文本传递(使用 javascript)到 href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
例如,当我点击关于链接必须是 example.com/tag/about/
这是我的答案。我正在使用 Javascript 来操作 DOM 以添加一个新元素,其 href 等于 span 元素中的内部文本。
我希望你觉得这个答案有帮助。谢谢。
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
让我们使用纯 javascript,我知道您想使用 jQuery,但我真的很确定,如果不使用纯 javascript 浏览网页,太多人无法做到这一点。所以这里有一个好方法。
您可以从jsFiddle关注它
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
让我们处理代码,
var objectList = document.getElementsByClassName("tableCell");
现在我们有了类的所有元素tableCell
。这比$(".tableCell")
在太多情况下要好。objectList[x].addEventListener('click', function(){});
使用这种方法,我们为每个对象添加了事件。top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
如果有人单击带有类的元素,则使用此行:我们将链接更改为他的第一个子节点的文本。我希望它有用,如果您想提高自己,请尝试使用纯js。
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
你可以试试上面的代码
您没有链接,但跨越您的 html。但是,您可以构建href
您想要的并将其分配给现有链接:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
最简单的方法:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
如果您总是要让 url 以某些东西开头,您可以这样做。它的设置方式是...
prefix
+跨度文本+suffix
THE SPANS TEXT中的空格将转换为-
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
您可以轻松调整它,因此如果您希望它以.html
而不是结尾/
,您可以更改后缀。此方法还允许您使跨度具有大写的单词和空格。