jQuery $("img [src = the_image_souce]").attr('src','new_src');不起作用 [英] jQuery $("img[src=the_image_souce]").attr('src','new_src'); does not work

查看:139
本文介绍了jQuery $("img [src = the_image_souce]").attr('src','new_src');不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码不起作用,我不知道为什么 the_image_source和new_src只是占位符,我已经在其中放置了真实的值

My code does not work I don't know why the_image_source and new_src are just place holders I have put real values in them

我也尝试过$("img[src=the_image_souce]")[0].attr('src','new_src');,但是它也不起作用,请帮助

I have also tried $("img[src=the_image_souce]")[0].attr('src','new_src'); but it does not work either, please help

推荐答案

您必须知道通过访问jQuery Object中的[0]元素,这将返回DOM元素.您不能直接在DOM元素上使用jQuery attr()方法.它必须在jQuery对象上运行

You must be aware by accessing the [0] element in the jQuery Object this will return the DOM element. You cannot use the jQuery attr() method directly on a DOM element. It must be run on a jQuery Object

基本上,如果您将有多个与以下选择器匹配的元素,并且要访问第一个匹配的元素$("img[src='http://domain.com/image.jpg]"),则应使用 .eq().例子

Essentially, if you will have more than one element that matches the following selector and you want to access the first matched element $("img[src='http://domain.com/image.jpg]") then you should use .first() or .eq(). Example

$("img[src='http://domain.com/image.jpg']").first().attr('src','http://domain.com/newimage.jpg')

$("img[src='http://domain.com/image.jpg']").eq(0).attr('src','http://domain.com/newimage.jpg')

$($("img[src='http://domain.com/image.jpg']")[0]).attr('src','http://domain.com/newimage.jpg');

但这看起来很奇怪

这篇关于jQuery $("img [src = the_image_souce]").attr('src','new_src');不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆