2011-10-03 88 views
2

我在我的頁面上有<form> s,我想用<button> s代替。造成我困難的原因是我想使用<form>的提交輸入的值作爲按鈕的html。用jQuery代替元素

<form action="/postcomment/" method="post"> 
<inputs> 
. 
. 
. 
<input type="submit" value="Reply"> 
</form> 

變爲

<button class="postcomment">Reply</button> 

我有一個很難包裝我的腦海裏圍繞鏈接在這裏。我需要獲取數據值(例如「Reply」),然後將它們插入到一個jQuery操作中的按鈕元素中(或者用.index()來管理排序),但我還沒有弄清楚如何去做。

+1

我不知道我理解你的問題。 –

+0

編輯html不是更容易嗎? – timrwood

+1

你能否更普遍地解釋你正在努力完成什麼?你這樣做的方式似乎非常複雜和不尋常。 –

回答

2

工作示例這裏:http://jsfiddle.net/Mch86/

$(document).ready(function(){ 
    $('form').each(function(){ 
     button = $('<button>' + $('input[type="submit"]', this).val() + '</button>').addClass($(this).attr('action').replace(/\//g, '')); 
     $(this).replaceWith(button); 
    }); 
}); 
0

你可以這樣做:

var label = $('form input:submit').val(); 
var action = $('form').attr('action').replace(/\//g, ''); 

var button = $('<button />', { class: action}); 
button.html(label); 
$('form').replaceWith(button) 

;

小提琴這裏:http://jsfiddle.net/be3af/1/

1

做這樣的事情:

$('input[type="submit"]').replaceWith(function() { 
    return $('<button>').text(this.value).addClass('postcomment'); 
}); 

jsFiddle Demo

這將與<button>替換所有的提交按鈕(<input type="submit">)的,保持文本上的按鈕。

replaceWith()允許您使用一個函數作爲其參數,該函數引用了單個提交自己(this)。

+0

+1呵呵,我用了jQuery好幾年了,從來沒有注意過'replaceWith'。每天學點新東西...... – timrwood

+0

只替換提交按鈕 - 他說他想替換整個表單。 – Blazemonger

+1

我知道OP想要替換整個表單,而不僅僅是輸入。 – vzwick

1

既然你說你有多種形式:

$(function() { 
    $('form').each(function() { 
     var str = $(this).find('input[type="submit"]').val(); 
     $(this).replaceWith($('<button/>').addClass("postcomment").text(str)); 
    }); 
});