开发者

Finding the value/text of an A tag using JQuery

开发者 https://www.devze.com 2023-01-04 17:47 出处:网络
Something\'s not quite right here. $(document).ready(function() { $(\"a#edit\").click(function() { $(\"div#search\").addClass(\"hidden\");

Something's not quite right here.

$(document).ready(function() 
        { 
            $("a#edit").click(function() {
                $("div#search").addClass("hidden");
                $("div#edit").removeClass("hidden");
            alert((this).val());
            return false;
            }); 
        } 
); 
开发者_如何学C

And later:

<a href="#" id="edit">10.1001</a>

I want to get the value "10.1001" from this. alert((this).val()); doesn't seem to work, nor does alert((this).text());. Can someone point out really quickly what I'm missing here? Thanks!


Instead of (this).val() you want $(this).text() for anchors.

.val() is for input type elements, .text() is used to get the text within a tag :)

Your code should look like this overall, note the addd $ before (this):

$(function() {
  $("a#edit").click(function() {
    $("div#search").addClass("hidden");
    $("div#edit").removeClass("hidden");
    alert($(this).val());
    return false;
  });
}); 


You seem to be forgetting the crucial $ symbol (an alias for jQuery), which when followed by parenthesis ((...)), calls the jQuery constructor and provides all of its methods.

Try:

alert( $(this).text() );

The keyword this actually provides a reference to the DOM element being clicked, and methods like val and text are not implemented on DOMElement. By wrapping a DOM element in a jQuery object you can get access to these methods.


Try:

$(document).ready(function() 
        { 
            $("a#edit").click(function() {
                $("div#search").addClass("hidden");
                $("div#edit").removeClass("hidden");
            alert($(this).text()); // $(this).text() should return the text contained within the relevant tag.
            return false;
            }); 
        } 
);
0

精彩评论

暂无评论...
验证码 换一张
取 消