簡體   English   中英

Javascript,jQuery - 我做錯了什么?

[英]Javascript , jQuery - what have I done wrong?

$(document).ready(function () {
    $("href").attr('href', 'title');
});

$('a[href$=.jpg]').each(function () {
    var imageSrc = $(this).attr('href');
    var img = $('<img />').attr('src', imageSrc).css('max-width', '300px').css('max-height', '200px').css('marginBottom', '10px').css('marginTop', '10px').attr('rel', 'lightbox');
    $(this).replaceWith(img);
});
});

這是我目前的jQuery代碼,我希望將所有鏈接'href更改為與其標題相同,然后再將它們嵌入到頁面中。 然而,隨着代碼中href更改為title位,它將停止工作。 我是Javascript的新手,所以我肯定做錯了什么,只是不確定是什么! 任何幫助非常感謝!

感謝大伙們

編輯

這是我要更改的html:

<p class="entry-content">Some interesting content<a href="http://example.com/index.php/attachment/11" title="example.com/file/testing-20101016T114047-2k5g3ud.jpeg" rel="external" class="attachment" id="attachment-11">http://example.com/index.php/attachment/11</a></p>

你改錯了,你試圖選擇href元素而不是a

這個修復應該這樣做:

$("a[title]").each(function() {
    $(this).attr('href',$(this).attr('title'));
});

它將選擇所有帶title a元素,並使用此值設置href

這是一種更有效的方式。

由於您只是替換<a>元素,因此實際上無需更改其href 只需選擇以jpg/jpeg結尾的<a>元素,並直接使用該屬性。

示例: http //jsfiddle.net/5ZBVf/4/

$(document).ready(function() {
    $("a[title$=.jpg],[title$=.jpeg]").replaceWith(function() {
            return $('<img />', {src:this.title, rel:'lightbox'})
                    .css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
    });
});​

你的.each().ready()函數之外。

您可以像這樣輕松完成href更改:

 $(document).ready(function () { $("a").attr('href', function() { return this.title; }); }); 

.attr()方法將接受一個函數,其中返回值是(在這種情況下) href的新值。

所以整件事情看起來像這樣:

示例: http //jsfiddle.net/5ZBVf/3/

 $(document).ready(function() { $("a[title]").attr('href', function() { return this.title; }) .filter('[href$=.jpg],[href$=.jpeg]') .replaceWith(function() { return $('<img />', {src:this.href, rel:'lightbox'}) .css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10}); }); }); 

嘗試:

$("a").each(function () {
    var $this = $(this);
    $this.attr('href', $this.attr('title'));
});

這一行:

$("href").attr('href','title');

找到所有href元素並用字符串'title'替換它們的href attr。 由於沒有href元素,請嘗試以下方法:

// for every anchor element on the page, replace it's href attribute with it's title attribute
$('a').each(function() {
  $(this).attr('href', $(this).attr('title');
});

看看這個: http//jsfiddle.net/TbMzD/似乎做你想要的。 注意:$(document).ready()由於jsfiddle而被注釋,你實際上需要在你的代碼中使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM