2

I am calling a jQuery method with HTML as the parameter.

I then want to check through the HTML for the input control with the class of "LastIdReceived". There will always only be one of these.

I then want to find the value that is set to this control (i.e.: the Id of the last control received).

However, the val() method is returning undefined. I wonder if this is because it is dynamic content and isn't part of the DOM.

If there is a way to get this, please could you share it.

Here is my function:

 function AfterLoadingMoreFollowersOpinions(data) {
    var htmlObject = $(data);
    var object = htmlObject.find('.LastIdReceived');
    alert(object.val());  
}

EDIT: My Controller is returning a PartialView as the ActionResult, which is then being given to the OnSuccess method of the Ajax call like so:

OnSuccess = "AfterLoadingMoreFollowersOpinions(data);"

I think it is passing the HTML correctly from this call, as doing an ALERT in the JS for both htmlObject and object are returning [object object] which makes me believe those parts of the JS are working (correct me if I am wrong. I don't know a better way to check).

The HTML that the PartialView renders and passes through (I am assuming) to the JS function is as follows:

<div>
<div class="PostedOpinionDiv" id="SkipToOpinion_1002">
<p><b>Id:</b> 1002</p>
<p><b>Author:</b> Joe Shmoe - 8</p>
<p><b>Opinion Subject:</b> Follower Opinion Subject - 2</p>
<p><b>Opinion:</b> Follower Opinion Text - 2</p>
</div>
<input type="hidden" class="LastIdReceived" value="1002" />
</div>

As you can see, it's the value of that input that I want to get from my JS function (1002).

4

1 回答 1

1

您可以使用 jquery 的 parseHTML() 方法将 HTML 文本用作 DOM,这是您给定示例的解决方案:

//Parse HMTL to DOM and find an item value
function AfterLoadingMoreFollowersOpinions(data) {
    var htmlObject = $.parseHTML(data);
    var object = $(htmlObject).find(".LastIdReceived");

    //alert item value
   alert(object.val());  
}

//Any HTML text
var htmlString = "<div>";
htmlString += "    <div class=\"PostedOpinionDiv\" id=\"SkipToOpinion_1002\">";
htmlString += "        <p><b>Id:</b> 1002</p>";
htmlString += "        <p><b>Author:</b> Joe Shmoe - 8</p>";
htmlString += "        <p><b>Opinion Subject:</b> Follower Opinion Subject - 2</p>";
htmlString += "        <p><b>Opinion:</b> Follower Opinion Text - 2</p>";
htmlString += "   </div>";
htmlString += "   <input type=\"hidden\" class=\"LastIdReceived\" value=\"1002\" />";
htmlString += "</div>";

//Call function and send HTML text
AfterLoadingMoreFollowersOpinions(htmlString);

看到工作:http: //jsfiddle.net/6ZH7v/1/

有兴趣的文档:http: //api.jquery.com/jQuery.parseHTML/

于 2013-11-06T17:10:50.613 回答