[英]Why doesn't jQuery “.css” work with variables?
.css()
在這種情況下有效:
if ($(toggle.targetEl).css('opacity') === '0') {
// some code
} else {
// more code
}
但是,如果執行此操作,將無法正常工作:
const $targetEl = $(toggle.targetEl)
if ($targetEl.css('opacity') === '0') {
// $targetEl.css('opacity') => undefined
這是jQuery的默認行為嗎? 還是我做錯了什么?
編輯:
最后一個示例不輸出任何錯誤。 console.log($targetEl)
顯示:
[prevObject: jQuery.fn.init[1], context: document, selector: ".map"]
編輯2:
指令.js:
export const toggle = {
update: function (toggle) {
const $el = $(this.el)
const $targetEl = $(toggle.targetEl)
console.log($targetEl)
$el.click(() => {
if ($targetEl.css('opacity') === '0') {
$(toggle.targetEl).css('visibility', 'visible')
$(toggle.targetEl).animate({ opacity: 1 }, 200)
} else {
// hide element when opacity animation is done
$(toggle.targetEl).animate({ opacity: 0 }, 200, () => {
$(toggle.targetEl).css('visibility', 'hidden')
})
}
})
}
}
component.vue:
<button class="toggle-map" v-toggle="toggle">
<i class="fa fa-map"></i>
</button>
<script>
export default {
data () {
return {
toggle: {
targetEl: '.map'
}
}
}
通過以下方式解決了這些問題:
const $el = $(this.el)
$el.click(() => {
const $targetEl = $(toggle.targetEl)
if ($targetEl.css('opacity') === '0') {
// some code
這是const
的作用域問題……盡管我不太確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.