【问题标题】:Set value of input html string with jquery用jquery设置输入html字符串的值
【发布时间】:2012-08-14 01:06:41
【问题描述】:

我在这样的字符串中有 HTML 的 sn-p:

var htmlString = '<input type="text" id="someID" name="someID">';

我如何使用 jQuery 设置它的值,以便 HTML 像这样结束:

'<input type="text" id="someID" name="someID" value="newValue">';

谢谢, 斯科特

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:
    $(htmlString).attr("value", "newValue");
    

    但这将返回 jQuery 对象,而不是字符串。您可以将其添加到 DOM。

    $(htmlString).attr("value", "newValue").appendTo("body"); // you can give any element instead of body
    

    编辑:

    您可以使用@idor_brad 的方法。这是最好的方法,否则

    var htmlString = '<input type="text" id="someID" name="someID">';
    
    var $htmlString = $(htmlString);
    $htmlString.attr("value1", "newValue1");
    $htmlString.attr("value2", "newValue2");
    $htmlString.attr("value3", "newValue3");
    
    console.log($htmlString.get(0).outerHTML);
    

    var htmlString = '<input type="text" id="someID" name="someID">';
    
    var $htmlString = $(htmlString);
    $htmlString.attr("value1", "newValue1");
    $htmlString.attr("value2", "newValue2");
    $htmlString.attr("value3", "newValue3");
    
    console.log($("<div>").append($htmlString).html());
    

    【讨论】:

    • 我知道...我想也许你已经找到了一种不使用 DOM 的聪明方法。哦,好吧:)
    • 您想在不使用 DOM 的情况下检索最终字符串吗?这也是可能的
    • 这让我大部分时间都在那里。如何从 jQuery 对象中取回 HTML 字符串?
    【解决方案2】:

    你只是想操纵字符串,对吧?给这只猫剥皮的方法有很多,但是

    var newString = htmlString.replace('>', ' value="newValue">');
    

    【讨论】:

      【解决方案3】:

      dom 准备好后,将输入附加到 body,然后使用 id = "someID" 获取输入并将其值设置为 newValue

         $(document).ready(function(){
             $("body").append(htmlString);
             $("#someID").val("newValue");
          });
      

      【讨论】:

      • 这是最优雅的解决方案,因为我的 html 很复杂。
      【解决方案4】:

      您首先需要将元素添加到 DOM(即添加到您的网页)。例如:

      $(".container").append(htmlString);
      

      然后你可以访问你的 input 作为一个 jquery 对象并像这样添加 value 属性:

      $("#someID").val("newValue");
      

      -- See Demo --

      【讨论】:

        猜你喜欢
        • 2013-05-21
        • 1970-01-01
        • 2013-08-25
        • 1970-01-01
        • 2020-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        相关资源
        最近更新 更多