img CSS不会通过jQuery更新onclick

时间:2019-09-11 14:47:56

标签: javascript jquery css

我已经为此花了几个小时不停地动脑子,比以前更接近解决方案。我正在通过AJAX调用和JavaScript动态生成<img>标签,每个标签都有自己的唯一ID,并在生成时为它们提供某些边框颜色(标记它们是“好”还是“坏”)。

// the div that the screenshots go in
<div id ="screenshots_holder"> </div>


// the JS that is generating the screenshots

var screenshots_holder = document.getElementById("screenshots_holder");
var x = "";


for(i in data.screenshots) {

var image_name = data.screenshots[i].split("/")

x += '<img id="' + image_name[2] +'"src="/static/'; 
x += data.screenshots[i]; 
x += '" style = "height: auto; border-style: solid; border-width: 5px; border-color: #1ebe1e; max-width: 10%; margin-right: 10px; margin-bottom: 10px; "'; 
x += 'onclick="blueifyScreenshot(this.id)" >'; <-- the problem is here!!

}
screenshots_holder.innerHTML = x;

上面的代码工作得很好……减去了我添加onclick属性的最后一部分!

我正在尝试做到这一点,以便当我单击屏幕快照时,其边框会更改颜色,它会稍微缩放,并添加一个盒子阴影,所有这些都是通过名为{{1}的JavaScript函数完成的},它将图片的唯一ID作为参数,以便可以通过jQuery进行抓取。

现在,当我将鼠标悬停在上面时,我可以获取屏幕截图以执行此操作,但这不是永久的。不幸的是,我无法进行任何CSS更改。

现在,我正在通过jQuery id选择器抓取每个图像元素。我知道这是可行的,blueifyScreenshot(id)应该是正确的,因为我已经通过调试器中的HTML / JS断点对其进行了验证,并将其与要更改其边框的屏幕截图进行了匹配。 updated_id被调用,但是无论我做什么,CSS都没有改变。

我尝试使用blueifyScreenshot方法,该方法仅适用于现有元素(屏幕快照就是这样)。

.css

我尝试用function blueifyScreenshot(id) { console.log("#" + id); var updated_id = "#" + id; // this isn't changing anything $(updated_id).css({ "border-color": "#0614d1 !important", "cursor" : "pointer" , "transform": "scale(1.1)", "box-shadow": "0 0 12px #0614d1" }); } 添加一个类,并在我的.css表中定义它。

.addClass()

我什至尝试使用function blueifyScreenshot(id) { console.log("#" + id); var updated_id = "#" + id; // this isn't changing anything either.. $(updated_id).addClass('selected_screenshot'); } /* CSS */ .selected_screenshot { border-color: #0614d1 !important; cursor : pointer; transform: scale(1.1); box-shadow: 0 0 12px #0614d1; } 方法更新图像的样式属性。

.attr()

所有操作均无效,并且单击我的屏幕快照时不会更改。我尝试浏览StackOverflow以查看其他人是否遇到此问题,并且看起来每个人都可以通过我尝试的方法解决他们的问题。

有人能够协助我,或者发现我没有的东西吗?

1 个答案:

答案 0 :(得分:2)

仅引用元素

onclick="blueifyScreenshot(this)"

并切换课程

function blueifyScreenshot(elem) {
  elem.classList.toggle('active')
}

我个人只会使用dom方法

var images = [
  'http://placekitten.com/100/300',
  'http://placekitten.com/200/200',
  'http://placekitten.com/200/300',
  'http://placekitten.com/100/200'
]

var outElem = document.getElementById('out')

images.forEach(function(src) {
  var img = document.createElement('img');
  img.className = 'example'
  img.src = src
  img.addEventListener('click', function() {
    this.classList.toggle('selected')
  })
  outElem.appendChild(img)
})
img.example {
  height: auto;
  border-style: solid;
  border-width: 5px;
  border-color: #1ebe1e;
  max-width: 10%;
  margin-right: 10px;
  margin-bottom: 10px;
}

img.example.selected {
  border-color: #0614d1 !important;
  cursor: pointer;
  transform: scale(1.1);
  box-shadow: 0 0 12px #0614d1;
}
<div id="out"></div>