2010-10-06 23 views
0
$("a").each(function() { openFile($(this).attr('href')); } 

我從另一個問題得到了這個。 openFile是一個根據鏈接的文件擴展名切換img src的函數。我試圖根據鏈接的href更改數據,但它只執行一次

現在如果我有這樣的:

<a class="thelink" href="../General Reading/General Reading 1/Luddites/Luddites 4 Summary.pdf"><img class="theimage" src="" alt="icon"/> <div class="thefile"></div></a> 
<a class="thelink" href="../General Reading/General Reading 1/Luddites/Luddites 5 Reading.pdf"><img class="theimage" src="" alt="icon"/> <div class="thefile"></div></a> 
<a class="thelink" href="../General Reading/General Reading 1/Luddites/Luddites 1 Vocab.ppt"><img class="theimage" src="" alt="icon"/> <div class="thefile"></div></a>  
<a class="thelink" href="../General Reading/General Reading 1/Luddites/Luddites 2 Grammar Preview.ppt"><img class="theimage" src="" alt="icon"/> <div class="thefile"></div></a> 

我的功能僅在我想結束運行一次,並採取從最後一個URL的信息。我想要的是循環每個鏈接並根據特定鏈接更改信息。

Err很難解釋。

+2

放了console.log或者$(「a」)。(each(function(){..)中的alert(),並確保找到了正確數量的元素。如果是,則可能是openFile方法有問題 – sjobe 2010-10-06 18:24:41

回答

2

這樣的openFile功能不知道要定位哪個圖片。也許這會起作用呢?

$("a").each(function() { 
    var src = openFile($(this).attr('href')); 
    $(this).find('img').attr('src',src); 
}); 

function openFile(href) { 
    // do stuff 
    // and make sure the src is returned 
    return 'something'; 
} 

或圖像對象添加到中openFile功能,這樣你就可以從那裏瞄準它:

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

function openFile(href, img) { 
    // do stuff 
    img.attr('src', something); 
} 

或者乾脆納入openFile功能jQuery的電話:

$("a").each(function() { 
    // do stuff with $(this).attr('href') 
    // change $(this).find('img').attr('src',src); 
});
0

你不需要在包含a的控件上執行.each嗎?而不是'a'控制本身?

+0

他正在循環文檔中的所有'a'元素。 – jball 2010-10-06 18:26:08

+0

我現在明白了..對不起! – Chris 2010-10-06 18:30:54

0

要麼通過這個作爲另一個參數中openFile,或者更好的做這樣的事情結合這中openFile:

$('a').each(openFile); 

然後

function openFile() 
{ 
//do stuff on $(this) 
} 
相關問題