【问题标题】:JQuery - Replace html button with <li> while keeping values intactJQuery - 用 <li> 替换 html 按钮,同时保持值不变
【发布时间】:2012-03-13 14:40:56
【问题描述】:

我有一个带有按钮的页面:

<input type="button" alue="TEST" 
style="height:40px;width:120px;"
 onClick="javascript:window.location='page.html';" /> 

我想把它转换成(webui):

<li><a href="page.html">TEST</a></li>

这是我到目前为止的代码:(似乎不起作用)

  $('<input type="button" value=').replaceWith('<li>');
    $('onClick="javascript:window.location=').replaceWith('<a href="');
     $('';" />').replaceWith('" target="_self"></a></li>"');

【问题讨论】:

  • 你不能那样做。
  • 为什么要将损坏的 HTML 发送到客户端,然后用 jQuery 修复它?这不是事情应该如何运作的。如果您可以更改该页面的 JavaScript,您也可以立即更改 HTML。

标签: c# javascript jquery model-view-controller


【解决方案1】:

或者用更一般的方式:

$("input[type='button']").replaceWith(function() {
   var $button = $(this);
   var $result = $("<a></a>");
   var target = $button.attr("onClick");
   target = target.substr(target.indexOf('\''));
   target = target.substr(0, target.length - 2);
   $result.attr("href", target);
   $result.text($button.val());
   $result = $("<li></li>").append($result);
   return $result;
});

现场示例:http://jsfiddle.net/ERLgR/1/

【讨论】:

  • 这可行,但我需要它是动态的。值 Test 将根据页面上的按钮而改变。添加到代码中容易吗?
  • 更正!你说对了!谢谢太好了!!
【解决方案2】:

您正在尝试对 jQuery 对象进行字符串替换,但这不是它的工作方式。你可以这样做:

$(':button[value="TEST"]').replaceWith($('<li><a href="page.html">TEST</a></li>​​​​'));​

此外,正如 Tomalak 在 cmets 中添加的那样,最好的办法是直接在 HTML 中更改它,而不是使用 javascript。

【讨论】:

    【解决方案3】:

    这似乎是一个普遍的坏主意,但无论如何这里有一个答案?

    var elm = $('input[type="button"]'),
        alue = elm.attr('alue'),
        page = elm.attr('onClick').split("'")[1],
        elm2 = '<li><a href="'+page+'">'+alue+'</a></li>';
    elm.replaceWith(elm2)​;​​​​​​​​​​​​​
    

    FIDDLE

    【讨论】:

    • 这行得通,但我需要它是动态的。值 Test 将根据页面上的按钮而改变。添加到代码中容易吗?
    • @user719825 - 只需删除“alue”的选择器匹配!编辑了我的答案。
    猜你喜欢
    • 2013-05-20
    • 2013-03-14
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多