javascript - 为什么 jQuery 选择器不起作用?

标签 javascript jquery

为什么这不起作用?

        $(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").attr("href");

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

            alert(RegExp.$3);

        });

    </script>

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

最佳答案

.replaceWith()之后调用时,页面上没有 ID 为 test 的元素。看来您打算使用 .html().append()而不是 .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");

关于javascript - 为什么 jQuery 选择器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151789/

相关文章:

javascript - Jvector map,如何聚焦在一个标记上?

jQuery Draggable 脱离了它的父级

javascript - Web 音频 MediaElementSource 节点未进行垃圾回收

javascript - 为什么手动触发事件时回调中的事件 e 未定义?

javascript - 以最快的乘法方式乘以大数

jQuery onclick 切换类名

jquery - 光滑的旋转木马图像不垂直适合屏幕且不垂直居中

javascript - 隐藏文本动画无法正常工作

javascript - 如何将具有背景的 <span> 定位到中心?

javascript - JQuery Datepicker 不会更改输入值