JavaScript 将字符串 hrefs 转换为 onClicks

JavaScript convert string hrefs into onClicks

我有多个标准链接的字符串,例如

<a href="http://example.com">Name of Link</a>

我正在尝试将它们变成

<a onClick="myFunc('http://example.com','Name of Link')">Name of Link</a>

甚至只是:

<a onClick="myFunc('http://example.com')">Name of Link</a>

如果前者不必要地困难,那就太好了。链接被动态插入到 DOM 中,因此事件处理程序不会执行。

您需要阻止默认操作的事件处理程序并获得 href

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

for (var i=anchors.length; i--;) {
    anchors[i].addEventListener('click', func, false);
}

function func(e) {
    e.preventDefault();
    var href = this.getAttribute('href'),
        text = this.innerText;
    myFunc(href, text);
}

FIDDLE

如果你必须使用字符串,你可以这样做

var str = '<a href="http://example1.com">Name of Link 1</a><br /><a href="http://example2.com">Name of Link 2</a><br /><a href="http://example3.com">Name of Link 3</a><br /><a href="http://example4.com">Name of Link 4</a>';

var parser  = new DOMParser();
var doc     = parser.parseFromString(str, "text/html");
var anchors = doc.getElementsByTagName('a');

for (var i=anchors.length; i--;) {
    var href = anchors[i].getAttribute('href'),
        text = anchors[i].innerText;
        
    anchors[i].setAttribute('onclick', "myFunc('"+href+"', '"+text+"')");
    anchors[i].removeAttribute('href');
}

str = doc.body.innerHTML;

document.body.innerHTML = str;

function myFunc(href, text) {
  alert(href + ' - ' + text);
}

你可以这样做

HTML

<a href="http://example.com" onclick="myFunction(this.href,this.textContent)">
  My link
</a>

JS

function myFunction(getAttr,text){
console.log(getAttr,text);

}

EXAMPLE

编辑

如果您想禁止 href 操作,那么您必须使用

event.preventDefault();

已更新 JS

function myFunction(event,getAttr,text){
event.preventDefault();
console.log(getAttr,text);
}

UPDATED JSFIDDLE

Append your string in a temporary element and manipulate it as explained by adeneo

试试这个:

var str = '<a href="http://example.com">Name of Link</a>';
var elem = document.createElement('div');
elem.innerHTML = str;
var targetEleme = elem.getElementsByTagName('a')[0];
targetEleme.addEventListener('click', function(e) {
  e.preventDefault();
  var href = this.getAttribute('href'),
    text = this.innerText;
  myFunc(href, text);
});
document.body.appendChild(targetEleme);

function myFunc(href, text) {
  alert('HREF: ' + href + '   TEXT: ' + text);
}

Fiddle here