通过jQuery访问div中的span文本

时间:2021-06-17 20:28:21

I'm trying to change the text inside of a span tag in a Rails app.

我正在尝试更改Rails应用程序中span标记内的文本。

<% @steps.each do |step| %>
  <div class="step_number">
    <span class="step_order_text"><%= step.order %></span>
  </div>              
<% end %>

I'd like to use a jQuery function to loop over all the 'step_order_text' classes which are created in the multiple steps, like so:

我想使用jQuery函数循环遍历在多个步骤中创建的所有'step_order_text'类,如下所示:

stepNums = $('.step_order_text');
    for(i in stepNums){
        var q = stepNums.get(i);
        q.text(updated_order[i].position);

    }

The problem is, I keep getting this error:

问题是,我一直收到这个错误:

Uncaught TypeError: q.text is not a function

Any thoughts? Seems simple but I've been stuck on this for quite a while. Thank you in advance and hope everyone has a great weekend!

有什么想法吗?看似简单,但我已经坚持了很长一段时间。提前谢谢你,希望大家周末愉快!

2 个解决方案

#1


1  

Use .each() to loop through a jQuery collection. Within the function body, this refers to the current element of the loop.

使用.each()循环遍历jQuery集合。在函数体内,这指的是循环的当前元素。

stepNums.each(function(i) {
    $(this).text(updated_order[i].position);
});

#2


1  

If I'm not mistaken the stepNums variable will be a collection of DOM elements.

如果我没弄错,stepNums变量将是DOM元素的集合。

stepNums = $('.step_order_text');
for(i in stepNums){
    var q = $(stepNums.get(i));
    q.text(updated_order[i].position.to_s);

}

I believe this will fix your issue. Either wrapping each element in $(..) or using the alternative innerText() function

我相信这会解决你的问题。将每个元素包装在$(..)中或使用替代的innerText()函数

#1


1  

Use .each() to loop through a jQuery collection. Within the function body, this refers to the current element of the loop.

使用.each()循环遍历jQuery集合。在函数体内,这指的是循环的当前元素。

stepNums.each(function(i) {
    $(this).text(updated_order[i].position);
});

#2


1  

If I'm not mistaken the stepNums variable will be a collection of DOM elements.

如果我没弄错,stepNums变量将是DOM元素的集合。

stepNums = $('.step_order_text');
for(i in stepNums){
    var q = $(stepNums.get(i));
    q.text(updated_order[i].position.to_s);

}

I believe this will fix your issue. Either wrapping each element in $(..) or using the alternative innerText() function

我相信这会解决你的问题。将每个元素包装在$(..)中或使用替代的innerText()函数