使用 jquery 更改嵌套在随机 html 元素中的 html 元素

Change html element nested inside a random html element with jquery

本文关键字:html 元素 随机 jquery 嵌套 使用      更新时间:2023-09-26

我有一个JQuery函数,可以在充满DIV的页面中随机选择一个DIV。我正在尝试修改函数,以便它检查嵌套在随机 DIV 中的 H3 标签的长度。如果 H3 标记中的字符串长度超过 10 个字符(包括空格),则该函数应截断字符串并将 H3 的内容替换为这个新的较短字符串并显示它。

例:(j查询)

if ($('#main').length !== 0) {
    var new_item = $('#main div').eq(Math.floor(Math.random() * $('#main div').length));    
    new_item.css('display','block');
}

(网页文件)

<div id="main">
  <div id="m1" style="display:none;">
    <h3>Apples are red</h3>
  </div>
  <div id="m2" style="display:none;">
    <h3>Oranges are orange</h3>
  </div>
  <div id="m3" style="display:none;">
    <h3>Bananas are yellow</h3>
  </div>
</div>

(期望的输出 - 如果随机选择 DIV#m2,用户会看到什么)

橙子

$(new_item).find('h3').text($(new_item).find('h3').text().substr(0,10));

您已经拥有获取随机div元素的代码。 您要添加的部分相当微不足道:

var h3_item = new_item.children("h3");
h3_item.html(h3_item.html().substring(0, 10));