Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

jquery - Finding text of an element within a HTML string

I am trying to load products number with AJAX. The code will be more complicated but to simplify the question, there is a block on the /category-one/

<div id="products-count">6</div>

Let's say, I am on any other page, home for example. I am trying to get that "6". I have tried the following but the alert is empty.

var url = '/category-one/';

$.ajax({
    url: url,
    success: function(data) {
        var $fullContent = $('#products-count', data)
        var text = $fullContent.text();
        alert(text);
    }
});

What is wrong with this code? Thank you for your help in advance.

question from:https://stackoverflow.com/questions/65903871/finding-text-of-an-element-within-a-html-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that for a contextual selector to work the second argument of the jQuery object needs to be an Element or jQuery object, or a selector string (ref). Given the context of your code, I would presume data holds HTML, not a selector.

To fix the issue you can provide data to a jQuery object and then find() the required element:

var url = '/category-one/';
$.ajax({
  url: url,
  success: function(data) {
    let $data = $(data);
    let $fullContent = $data.find('#products-count');
    let text = $fullContent.text();
    console.log(text);
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...