gpt4 book ai didi

javascript - jquery在appendTo之前初始化后将属性添加到存储在变量中的元素

转载 作者:行者123 更新时间:2023-11-30 11:21:51 28 4
gpt4 key购买 nike

在我当前的解决方案中,我定义了一个元素,然后解析了几个用于向该元素添加属性的 if() 语句。我知道 create、appendTo、add attribute 的顺序不正确。那么有哪些替代方案

当前有效的解决方案,在创建后添加 attr初始化->appendTo->添加属性

var myElement=$('<img />',
{
id:'myId',
})

$("#myDiv").append(myElement);


if(myVar === "val1"){
$("#myId").attr("src","img/img_01.png");
$("#myId").attr("title","Platform");
}
if(myVar === "val2"){
$("#myId").attr("src","img/img_02.png");
$("#myId").attr("title","Speaker");
}

不起作用,create->add attr->appendTo

 var myElement=$('<img />',
{
id:'myId',
})

if(myVar === "val1"){
$("#myId").attr("src","img/img_01.png");
$("#myId").attr("title","Platform");
}
if(myVar === "val2"){
$("#myId").attr("src","img/img_02.png");
$("#myId").attr("title","Speaker");
}
$("#myDiv").append(myElement);

尝试添加到变量对象,不起作用

var myElement=$('<img />',
{
id:'myId',
})

if(myVar === "val1"){
myElement["src"]="img/img_01.png";
myElement["title"]="Platform";
}

$("#myDiv").append(myElement);

最佳答案

在你上次的尝试中,你非常接近。将其更改为:

myElement["src"]="img/img_01.png";

到:

myElement["attr"]("src","img/img_01.png");

var myVar = 'val2';
var myElement = $('<img />', {id: 'myId'});
if(myVar === "val1"){
myElement["attr"]("src","img/img_01.png");
myElement["attr"]("title","Platform");
}
if(myVar === "val2"){
myElement["attr"]("src","img/img_02.png");
myElement["attr"]("title","Speaker");
}

$("#myDiv").append(myElement);
console.log($("#myDiv")[0].outerHTML);




/*
ANOTHER WAY: ........
var myElement = $('<img />', {
id: 'myId',
src: (myVar === "val1") ? "img/img_01.png" : (myVar === "val2") ? "img/img_02.png" : '',
title: (myVar === "val1") ? "Platform" : (myVar === "val2") ? "Speaker" : ''
})
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="myDiv"></div>

关于javascript - jquery在appendTo之前初始化后将属性添加到存储在变量中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562227/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com