我在DOM中獲得了一個錨點,下面的代碼用一個奇特的按鈕替換它。這工作得很好,但如果我想要更多的按鈕,它崩潰。我可以做到沒有for循環嗎?有幾個元素的JQuery問題
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
它是如何崩潰的? –
'$( 'a.makeabutton')'返回元素的集合,用'button.each(功能...)' – Ibu
的DOM看起來是這樣的: \t
\t \t Buttonized! \t \t
\t \t Buttonized! \t \t
\t \t Buttonized! \t \t
\t \t \t