[英]Jquery make two functions run together
我有一個搜索按鈕,我想在其中單擊時同時更改圖標以及邊框的顏色:
$(function () {
$("#search").click(function () {
$("#search").css({ "border": "2px", "border-style": "ridge", "border-color": "#000000" })
});
$("#search").click(function () {
$("#search").replaceWith($('<img>', { src: 'Icons/magnifier.png' }))
});
});
現在,我的兩個函數可以單獨工作,但是當我將這兩個函數結合在一起時(如我的示例),只有最后一個觸發。
有沒有一種方法可以組合這兩種功能,以便單擊時邊框和圖像都可以改變?
包裝盒的CSS:
.topnav img {
border: 2px ridge #7ab5dc;
position: relative;
height: 20px;
width: 20px;
float: right;
margin-top:15px;
margin-right:20px;
padding:3px;
border-radius: 5px;
}
HTML
<div class="topnav">
<img id="search" class="search" src="Icons/magnifier2.png" />
</div>
發生這種情況是因為第二次聲明$("#search").click(function () { ...
您將覆蓋第一個函數。因此,只需將要發生的所有事情都放在同一個.click
函數中
每行之后還需要分號。
根據@ jbehrens94關於ID丟失的說明,這是我的最終代碼
$("#search").click(function () {
$(this).replaceWith($('<img id="search">', { src: 'Icons/magnifier.png' })).css({ "border": "2px", "border-style": "ridge", "border-color": "#000000" });
});
1)調用.replaceWith($("<img>"), ...)
,不會將搜索ID保留到圖像中。
更新: .replaceWith($("<img id='search'>"), ...)
2)在編輯答案之前,我已經給了您建議。
$(function(){
var search = $('#search');
search.click(function(){
search.replaceWith(...).css(...);
});
});
這樣,您的代碼只需進入DOM一次即可獲取HTML。 這是一種出色的性能,並且還可以確保您正在使用想要的元素。
3)您還詢問了有關淡入/淡出的問題。 您可以使用jQuery的fadeIn(duration, completeCallback)
和fadeOut(duration, completeCallback)
函數。 持續時間以毫秒為單位,回調是一個匿名函數,但您也可以調用另一個函數。
$("#search").fadeIn(400, function(){ alert("Faded in"); });
@Jeppe我剛剛嘗試了不同的方法
.topnav img{
border: 2px ridge #7ab5dc;
position: relative;
height: 20px;
width: 20px;
float:right;
margin-top:15px;
margin-right:20px;
padding:3px;
border-radius: 5px;
}
.border-change{
border: 2px ridge #000000 !important;
}
您的HTML
<div class="topnav">
<img id="search" class="search" src="Icons/magnifier2.jpg" />
</div>
新的單行jQuery
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
$("#search").click(function () {
$("#search").addClass("border-change").attr("src","Icons/magnifier.jpg");
});
此線程中有很多帖子,我只想將對我有用的代碼發布給可能有相同問題的用戶:
$(function () {
var search = $("#search");
search.click(function () {
search.attr("src", "Icons/magnifier.png").css({ "border": "2px", "border-style": "solid", "border-color": "#808080", "padding-left": "130px", "transition": "all 500ms" });
});
$('html').click(function (e) {
if (e.target.id != 'search') {
$("#search").attr("src", "Icons/magnifier2.png");
$("#search").removeAttr('style');;
}
});
})
您可以像這樣在單個代碼中包含動作
$(“#search”)。click(function(){
$("#search").css({ "border": "2px", "border-style": "ridge", "border-color": "#000000" }).replaceWith($('<img>', { src: 'Icons/magnifier.png' }));
});
或可能被使用
$(“#search”)。click(function(){
$("#search").css({ "border": "2px", "border-style": "ridge", "border-color": "#000000" }).html($('<img>', { src: 'Icons/magnifier.png' }));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.