JavaScript将字符串href转换为onClicks

时间:2016-01-18 05:25:29

标签: javascript regex onclick href

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

<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中,因此事件处理程序不会这样做。

3 个答案:

答案 0 :(得分:1)

您需要事件处理程序来阻止默认操作并获取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

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

&#13;
&#13;
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);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做

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

答案 2 :(得分:0)

  

将您的string附加到临时element并按照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