开发者

Why jQuery selector is not working?

开发者 https://www.devze.com 2023-03-30 02:07 出处:网络
Why is this not working? $(document).ready(function(){ var content = \'<a href=\"http://example.com/index.php><b>Some text!</b></a> - <a href=\"http://example.com/index.ph

Why is this not working?

        $(document).ready(function(){

            var content = '<a href="http://example.com/index.php><b>Some text!</b></a> - <a href="http://example.com/index.php" class="ot-origin-anchor">News</a>';

            $("#test").replaceWith(function(){

                return content;

            });
            //Here is the problem. I don't know why but I can't define adres.
            var adres = $("#test .ot-origin-anchor").a开发者_如何转开发ttr("href");

            //find example.com - ugly :P
            var adresRegExp = adres.match(/(\w+:\/\/+(www.|))([^/]+)/);

            alert(RegExp.$3);

        });

    </script>

    <div id="test">bnb</div>


After the .replaceWith() call, there is no element on the page with ID test. It looks like you meant to use .html() or .append() instead of .replaceWith().

var content = '<a href="http://example.com/index.php><b>Some text!</b></a> - <a href="http://example.com/index.php" class="ot-origin-anchor">News</a>';

$("#test").html(content);
// or
$("#test").append(content);

var adres = $("#test .ot-origin-anchor").attr("href");


replaceWith replaces every element in the selection to which it is applied. That would mean you'd end up with just content after the replace. So your next query, which looks for #test would match nothing. #test is gone. You replaced it with content.


You are replacing #test with your content variable so the selector isn't finding an element with id test. Try $("#test").html(content); instead.

Updated jsfiddle: http://jsfiddle.net/sHGrB/


Why use replace with? Use the jQuery .html() method to add it to the DOM, after that, you should be able to select it easily. Working Example.


If you replace:

 $("#test").replaceWith(function(){

            return content;

        });

with:

$("#test").html(content);

You will get you the results you want, because #test no longer exists with replace


There are a couple problems here, one is that replaceWith is actually replacing #test with content. Then, your selector is looking for #test .ot-origin-anchor which doesn't exist, because #test was clobbered. Instead you should do something like:

$(document).ready(function(){
    var content = '<a href="http://example.com/index.php><b>Some text!</b></a> - <a href="http://example.com/index.php" class="ot-origin-anchor">News</a>';

    $("#test").html(content);
    var address = $("#test .ot-origin-anchor").attr("href");
    var addressRegExp = address.match(/(\w+:\/\/+(www.|))([^/]+)/);

    alert(RegExp.$3);
});
0

精彩评论

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