为什么这个Javascript没有添加到HTML中
此脚本将创建新元素并为其提供正确的ID,但不会加载到下面的HTML/字符串中:为什么这个Javascript没有添加到HTML中,javascript,jquery,html,css,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
<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>
$(函数(){
$(“#测试img”)。在(“单击”,函数(e){
var titleEl=document.createElement(“div”);
var laptopImg=$(“测试img”);
var theText=“这是一项测试”
文件.正文.附件(标题);
titleEl.id=“img title”;
titleEl.html=文本;
titleEl.position=laptopImg.position;
});
});
#img标题{
颜色:黑色;
z指数:1;
}
#测试img{
位置:绝对位置;
变换:比例(1,1);
-moz转换持续时间:2s;
}
#测试img:悬停{
变换:缩放(.5,.5);
-moz转换持续时间:2s;
}
#测试img:激活{
-moz变换:倾斜(360);
-moz转换持续时间:2s;
}
我尝试过各种函数,如.val.appendChild等。。。但似乎都不管用。它只是在每次单击图像时创建一个新的空div 作为原始解决方案,您需要使用
$(函数(){
$(“#测试img”)。在(“单击”,函数(e){
var titleEl=document.createElement(“div”);
var laptopImg=$(“测试img”);
var theText=“这是一项测试”
文件.正文.附件(标题);
titleEl.id=“img title”;
titleEl.innerHTML=文本;
titleEl.style.position=laptopImg.css('position');
});
});
演示:
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')
});
});
$(函数(){
var$laptopImg=$(“#测试img”)。在(“单击”上,函数(e){
var theText=“这是一项测试”
$div=$(''{
id:“img标题”,
位置:$laptopImg.css('position'),
html:文本
}).appendTo('正文')
});
});
演示:
注意:如果多次单击,还需要确保没有重复的ID此代码段应该为您添加div
$(function() {
$("#test img").on("click", function(e) {
var laptopImg = $("#test img");
$('<div id="img-title"><p>this is a test</p></div>')
.appendTo(document.body)
.css('position', 'absolute')
.offset(laptopImg.offset());
});
});
$(函数(){
$(“#测试img”)。在(“单击”,函数(e){
var laptopImg=$(“测试img”);
$(“这是一个测试”
.appendTo(document.body)
.css('位置','绝对')
.offset(laptopImg.offset());
});
});
为什么混合使用jQuery和本机DOM方法?此外,属性.html
和.position
不存在-这就是它不起作用的原因代码>@Stuart neater,我喜欢
$(function() {
$("#test img").on("click", function(e) {
var laptopImg = $("#test img");
$('<div id="img-title"><p>this is a test</p></div>')
.appendTo(document.body)
.css('position', 'absolute')
.offset(laptopImg.offset());
});
});