【问题标题】:How to get span tag inside a div in jQuery and assign a text?如何在 jQuery 中的 div 中获取 span 标签并分配文本?
【发布时间】:2011-02-10 00:18:10
【问题描述】:

我使用以下,

<div id='message' style="display: none;">
  <span></span>
 <a href="#" class="close-notify">X</a>
</div>

现在我想在 div 中找到 span 并为其分配一个文本...

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

【问题讨论】:

    标签: jquery find elements


    【解决方案1】:

    试试这个:

    $("#message span").text("hello world!");
    

    在您的代码中查看!

    function Errormessage(txt) {
        var m = $("#message");
    
        // set text before displaying message
        m.children("span").text(txt);
    
        // bind close listener
        m.children("a.close-notify").click(function(){
          m.fadeOut("slow");
        });
    
        // display message
        m.fadeIn("slow");
    }
    

    【讨论】:

    • @rahul,我有点困惑。不用担心:)
    【解决方案2】:
    $("#message > span").text("your text");
    

    $("#message").find("span").text("your text");
    

    $("span","#message").text("your text");
    

    $("#message > a.close-notify").siblings('span').text("your text");
    

    【讨论】:

    • 如果你已经有了message的JQuery对象呢?
    • @douglasg14b 我也有同样的问题。
    【解决方案3】:

    试试这个

    $("#message span").text("hello world!");
    
    function Errormessage(txt) {
        var elem = $("#message");
        elem.fadeIn("slow");
        // find the span inside the div and assign a text
        elem.children("span").text("your text");
    
        elem.children("a.close-notify").click(function() {
            elem.fadeOut("slow");
        });
    }
    

    【讨论】:

    • @rahul,你应该在显示#message的内容之前设置文本并绑定监听器
    【解决方案4】:
    function Errormessage(txt) {
        $("#message").fadeIn("slow");
        $("#message span:first").text(txt);
        // find the span inside the div and assign a text
        $("#message a.close-notify").click(function() {
            $("#message").fadeOut("slow");
        });
    }
    

    【讨论】:

      【解决方案5】:

      原版 JS,没有 jQuery:

      document.querySelector('#message span').innerHTML = 'hello world!'
      

      适用于所有浏览器:https://caniuse.com/#search=querySelector

      【讨论】:

        【解决方案6】:

        它会在标签中找到标签并将文本设置为跨度。

        $('div').find('span').text('你的文字');

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-26
          • 1970-01-01
          • 1970-01-01
          • 2015-03-03
          • 1970-01-01
          • 2014-01-10
          • 2016-01-22
          相关资源
          最近更新 更多