.text 未获取所有文本,但在控制台中工作

.text not getting all text, but works in console

本文关键字:控制台 工作 文本 获取 text      更新时间:2023-09-26

我正在尝试从表格单元格类中获取文本。该脚本在控制台中运行良好。但是,当我实现代码时,它只抓取部分文本。

<script type="text/javascript">
    var getCustomText = $( "td.product-title-cell" ).text();
    $(function () {
        $('#idToPutCustomText').val(getCustomText);
    });
</script>

TD 我正在尝试获取文本

<td class="product-title-cell"> <a href="/products/yellow-unicorn-award-trophy">Yellow Unicorn Award Trophy - 2014 / The Weird Animal Awards / Presented To: adsf / For: asdf2 / Additional Text: asdf3</a> </td>

我实际得到的文字

黄色独角兽便便奖杯 - 2014/怪异动物奖

笔记

"呈现给",此后的所有文本都会从某个地方调用。我还没能弄清楚。这让我相信对 PRESENTS to 的调用是在加载脚本后发生的。

我如何尝试使脚本加载持久

  • 我把它放在关闭身体标签之前和之后。
  • 我已经将代码放在它自己的文件中并使用它调用它。脚本被调用,但它没有得到任何文本。

    var theScript = document.createElement("script");
    theScript.setAttribute("type","text/javascript");
    theScript.setAttribute("src","//www.mysite.com/script.js");
    document.getElementsByTagName("head")[0].appendChild(theScript);
    

问题

    除了文本
  • 被切断之外,还有其他原因吗它是最后加载的?

  • 如果没有,绝对加载我的脚本的确定方式是什么最后?

这就是

在jQuery中使用document.ready的意义所在。它一直等到所有 DOM 元素都加载完毕,然后执行脚本:

$( document ).ready(function() {
    var getCustomText = $( "td.product-title-cell" ).text();
    $('#idToPutCustomText').val(getCustomText);
});

你需要将所有的jQuery操作加载到一个现成的包装器中,如下所示:

$(function(){
  // jQuery now available
  var getCustomText = $( "td.product-title-cell" ).text();
  $('#idToPutCustomText').val(getCustomText);
);

已经走到了一半......你只是把第一行留在外面:)

http://jsfiddle.net/mpwzu78w/

您必须选择该链接。您可以为链接指定类或 ID。

var getCustomText = $("a").text();
alert(getCustomText);