javascript - 为什么这个 Javascript 没有添加到 HTML 中

标签 javascript jquery html css

此脚本将创建一个新元素并为其提供正确的 ID,但不会加载到下面的 HTML/字符串中:

<script>
$(function () {
    $("#test img").on("click", function (e) {
        var titleEl = document.createElement("div");
        var laptopImg = $("#test img");
        var theText = "<p>this is a test</p>"
        document.body.appendChild(titleEl);
        titleEl.id = "img-title";
        titleEl.html = theText;
        titleEl.position = laptopImg.position;
    });
});
</script>
<style>
#img-title {
    color:black;
    z-index:1;
}
#test img {
    position: absolute;
    transform: scale(1,1);
    -moz-transition-duration: 2s;
}
#test img:hover {
    transform: scale(.5,.5);
    -moz-transition-duration: 2s;
}
#test img:active {
    -moz-transform:skew(360);
    -moz-transition-duration: 2s;
}
</style>
<div id="test">
    <%= image_tag('test_2.jpg') %>
</div>

我尝试了各种函数,例如 .val .appendChild 等...但似乎都不起作用。每次我单击图像时,它只会创建一个新的空 div。

最佳答案

作为原始解决方案,您需要使用 innerHTML

$(function() { 
    $("#test img").on("click", function(e) {

        var titleEl = document.createElement("div");
        var laptopImg = $("#test img");
        var theText = "<p>this is a test</p>"
        document.body.appendChild(titleEl);
        titleEl.id = "img-title";
        titleEl.innerHTML = theText ;
        titleEl.style.position = laptopImg.css('position'); 

    });

});

演示:Fiddle

jQuery-ish 解决方案将

$(function () {
    var $laptopImg = $("#test img").on("click", function (e) {
        var theText = "<p>this is a test</p>"
        $div = $('<div />', {
            id: 'img-title',
            position: $laptopImg.css('position'),
            html: theText
        }).appendTo('body')
    });
});

演示:Fiddle

注意:如果完成多次点击,还需要确保没有重复的 ID

关于javascript - 为什么这个 Javascript 没有添加到 HTML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18708751/

相关文章:

javascript - 基于用户输入的价格计算 React JS

javascript - 如何从 mapCenter 获取纬度和经度作为单独的变量

jquery - 实现 LinkedIn 的新自动填充功能 + 请求无法完成

jquery - jQuery 如何让 div 顺畅地跟随滚动?

javascript - jsPDF - 来自 HTML 和自定义字体

javascript - 数组中所有属性的组合

javascript - 在框架窗口的上下文中运行代码

javascript - 使用 Javascript 模仿 iOS 在选项卡之间滚动

javascript - react 意外 token : operator (<)

Javascript - onblur 事件在验证中创建无限警报循环