[英]Use jQuery. data() with select
我有下面的代码来动态更改图像。 它可以正常工作,但我有一些疑问:
1-为什么
$('#image').attr('data-picture-name', $this.val());
工作但是
$('#image').data('picture-name', $this.val());
不工作吗? 有没有办法使用data()而不是attr()?
2-从所选选项中的data-parameters值中检索数据
如何从选定选项的数据参数中获取值?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="docs-assets/ico/favicon.png">
<title></title>
</head>
<body>
<img data-picture-name="popol" src="" id="image" style="width: 1200px; height: 500px; border: 1px solid red;" />
<select name="meteo-list-cities" id="meteo-list-cities" class="triggered" data-trigger-change-call="meteo-country-change-trigger">
<option data-parameters="1" value="assets/images/newyork.jpg">New York</option>
<option data-parameters="2" value="assets/images/paris.jpg">Paris</option>
<option data-parameters="3" value="assets/images/london.jpg">London</option>
</select>
<script src="assets/js/plugins/jquery/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('#meteo-list-cities').on('change', function () {
var $this= $(this);
$('#image').attr('data-picture-name', $this.val());
$('#image').attr('src', $this.val());
});
});
</script>
</body>
</html>
是的,您可以使用数据存储其他信息。 您可以获取并设置该信息,使用jquery数据可以是简单字符串或复杂对象。 与设置属性不同,此数据对象从源视图中隐藏。
组
$('#image').data('cityImgPath', $this.val() );
$('#image').data('complexColorObj', { imgPath: "http://i.dailymail.co.uk/i/pix/2012/04/24/article-2134408-12BFD96D000005DC-434_964x788.jpg", color: "blue", mood: "depressed" } );
得到
var newImagePath = $('#image').data('cityImgPath');
var myMoodBeforeCoffee = $('#image').data('complexColorObj').mood;
一旦有了该变量,就可以将其应用于div
$('#image').attr('src', newImagePath );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.