简体   繁体   English

如何使用jQuery应用于所有href attr

[英]How to apply to all href attr using jQuery

How i do apply attr to all href's on my page. 我如何将attr应用于我页面上的所有href。 For example: I have : 例如:我有:

<ul>
    <li><a href="mylink1">mytext1</a></li>
    <li><a href="mylink2">mytext2</a></li>
    <li><a href="mylink3">mytext3</a></li>
</ul>

I need: 我需要:

<ul>
    <li><a href="javascript:myFunc(mylink1)">mytext1</a></li>
    <li><a href="javascript:myFunc(mylink2)">mytext2</a></li>
    <li><a href="javascript:myFunc(mylink3)">mytext3</a></li>
</ul>

I need do this without adding new id's, classes and etc. Use Js and jQuery. 我需要这样做而不添加新的id,类等。使用Js和jQuery。 Please, help! 请帮忙! :) :)

Something like this should work: 这样的事情应该有效:

$("ul li a").each(function(i, a) {
    a = $(a);
    a.attr('href', 'javascript:myFunc("' + a.attr('href') + '")');
});

Demonstration 示范

Note: this will apply this to only links within ul lists. 注意:这仅适用于ul列表中的链接。 To apply to all a tags across the entire page, use $("a")... instead. 适用于所有a整个页面标签,使用$("a")...来代替。

Also, this method may fail if the href attributes contain certain characters like " or \\ . If this is a possibility, then this is a bit safer: 此外,如果href属性包含某些字符(如"\\ " ,则此方法可能会失败。如果这是可能的话,那么这样会更安全一些:

$("ul li a").each(function(i, a) {
    a = $(a);
    a.attr('href', 'javascript:myFunc(' + JSON.stringify(a.attr('href')) + ')');
});

You can try like 你可以试试

$('a').each(function () {
    var att = $(this).attr('href');
    $(this).attr("href", "javascript:myFunc(" + att + ")");
});

Using jQuery: 使用jQuery:

$("a[href^='mylink']").on('click', function(e) {
    e.preventDefault();
   myFunc($(this).attr("href"));
});

this shoud do what you need: 这个应该做你所需要的:

$("a").each( function() {
  var url = $(this).attr('href');
  $(this).attr('href', 'javascript:myFunc("'+url+'")');
});

Instead of modifying the href assign the event handler in the actual Javascript: 不用修改href而是在实际的Javascript中分配事件处理程序:

$("[href]").click(function(e){
    e.preventDefault();
    myFunc(this.href);
});

function myFunc(value){
   alert(value);
}

JS Fiddle: http://jsfiddle.net/Rs9RH/ JS小提琴: http //jsfiddle.net/Rs9RH/

Try This: 尝试这个:

$('li a').each(function(){
$(this).attr('href',"javascript:myFunc("+$(this).attr('href')+")");
})

WORKING FIDDLE 工作时尚

I think this could works: 我认为这可行:

$("a[href^='mylink']").each(function () {
  var url = $(this).attr('href');
  $(this).attr("href", 'javascript:myFunc("'+url+'")')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM