Hyperlink 如何将链接名称复制到标题

Hyperlink 如何将链接名称复制到标题,hyperlink,copy,title,Hyperlink,Copy,Title,我想问一下如何在英语中更改标题 <a href="#" title="here">name</a> 所以我想让链接名自动复制到标题 所以如果我做了这个代码 <a href="#">title link</a> 到 如何在php或javascript中实现这一点 我懂一些php语言 但需要在数据库中创建链接中的所有单词,或者为每个链接变量创建链接$ 有人能帮我吗?在JQuery中,您可以通过了解当前标记并使用.attr()功能来更改属

我想问一下如何在英语中更改标题

<a href="#" title="here">name</a>

所以我想让链接名自动复制到标题

所以如果我做了这个代码

<a href="#">title link</a>


如何在php或javascript中实现这一点

我懂一些php语言

但需要在数据库中创建链接中的所有单词,或者为每个链接变量创建链接$


有人能帮我吗?

在JQuery中,您可以通过了解当前标记并使用.attr()功能来更改属性。类似于
$('a').attr('title','new_title')

我建议:

function textToTitle(elem, attr) {
    if (!elem || !attr) {
        // if function's called without an element/node,
        // or without a string (an attribute such as 'title',
        // 'data-customAttribute', etc...) then returns false and quits
        return false;
    }
    else {
        // if elem is  a node use that node, otherwise assume it's a
        // a string containing the id of an element, search for that element
        // and use that
        elem = elem.nodeType == 1 ? elem : document.getElementById(elem);
        // gets the text of the element (innerText for IE)
        var text = elem.textContent || elem.innerText;
        // sets the attribute
        elem.setAttribute(attr, text);
    }
}

var link = document.getElementsByTagName('a');

for (var i = 0, len = link.length; i < len; i++) {
    textToTitle(link[i], 'title');
}

.

如果您不想使用库:

var allLinks = document.getElementsByTagName('a');
for(var i = 0; i < allLinks.length; i++){
    allLinks[i].title = allLinks[i].innerHTML;
}

我认为
for()
中的
divs.length
应该是
allLinks.length
?是的,我刚刚更改了它,这是从我的一个项目中获取的。抱歉,我在html的block中添加了很多代码,所以只有这个block而不是所有页面。然后,您只需要编辑第一行,使其看起来像:
var allLinks=document.getElementById('whatever')。getElementsByTagName('a')。这将从#whatever中取出所有链接元素。在关闭
标记之前将其放入
标记中。它需要在构建DOM和元素可用后运行。thx工作正常,但如何使其用于html类或IDX中的元素这只适用于所有页面如果我想在html中获得大量代码块?
$('a').attr('title', function() { return $(this).text(); });
var allLinks = document.getElementsByTagName('a');
for(var i = 0; i < allLinks.length; i++){
    allLinks[i].title = allLinks[i].innerHTML;
}
var allLinks = document.getElementById('myelement').getElementsByTagName('a'); // gets all the link elements out of #myelement
for ( int i = 0; i < allLinks.length; i++ ){
    allLinks[i].title = allLinks[i].innerHTML;
}
$('a').each(function(){ // runs through each link element on the page
    $(this).attr('title', $(this).html()); // and changes the title to the text within itself ($(this).html())
});