用jQuery替换元素

时间:2011-10-03 16:26:23

标签: javascript jquery html

我的页面上有<form>我希望用<button>替换。导致我困难的是我想使用<form>的提交输入的值作为按钮的html。

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

变为

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

我很难在这里围绕链条缠身。我需要获取数据值(例如“Reply”),然后在一个jQuery操作中将它们插入到按钮元素中(或者用.index()之类的东西管理排序)我还没弄明白怎么做那个。

4 个答案:

答案 0 :(得分:2)

做这样的事情:

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

jsFiddle Demo

这会将所有提交按钮(<input type="submit">)替换为<button>,并将文字保留在按钮上。

replaceWith()允许您使用函数作为参数,该参数引用个人提交自己(this)。

答案 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);
    });
});

答案 2 :(得分:1)

既然你说你有多种形式:

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

答案 3 :(得分: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/