在AJAX结果上使用jquery更改图标

时间:2016-10-27 22:27:13

标签: jquery ajax font-awesome

点击链接后,我通过AJAX返回了一个列表。在列表中,我有一个字体很棒的链接,用于为列表条目添加书签。书签是通过AJAX完成的,这很好用,我的数据库是更新的。

但是,在更新后,我想将书签图标从fa-bookmark-o更改为fa-bookmark,并添加课程green以使图标变为绿色。这不起作用。代码如下。

HTML:

<a href="#" id="bookmark" class="bookmark" title="Bookmark" bookmark_id="12345"><i class="fa fa-bookmark-o"></i><i class="fa fa-bookmark"></i></a>

CSS

.bookmark:hover .fa-bookmark-o,
.bookmark .fa-bookmark 
{
color: #27ae60;
display: none;
text-decoration: none;
}
.bookmark:hover .fa-bookmark 
{
color: #27ae60;
display: inline;
text-decoration: none;
}

SCRIPT

<script type="text/javascript">
    $(document).on('click', '#bookmark', function(e) {
        var bookmark_id = $(this).attr('bookmark_id');

        $("#loaderIcon").show();
        $.ajax({
            type: 'POST',
            url: '<?php echo base_url(); ?>bookmark',
            data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', bookmark_id},
            dataType: 'json',
            success:function(data){
                if(data.status == 'X')
                {
                    $(this).find('i').removeClass('fa-bookmark-o');
                    $(this).find('i').addClass('fa-bookmark');
                    $(this).find('i').addClass('green');
                }
            },
        });
    });
</script>

2 个答案:

答案 0 :(得分:3)

AJAX调用的回调中的

this与事件处理程序上的不同。

有多种解决方案,最简单的解决方案是将变量存储在闭包中并在AJAX处理程序中使用

$(document).on('click', '#bookmark', function(e) {
    var me = $(this);
    var bookmark_id = me.attr('bookmark_id');

    $("#loaderIcon").show();
    $.ajax({
        type: 'POST',
        url: '<?php echo base_url(); ?>bookmark',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', bookmark_id},
        dataType: 'json',
        success:function(data){
            if(data.status == 'X')
            {
                me.find('i').removeClass('fa-bookmark-o');
                me.find('i').addClass('fa-bookmark');
                me.find('i').addClass('green');
            }
        },
    });
  });

还有其他可能的改进,但我专注于解决问题的最少变化

其他方式:胖箭头功能,Function.bind

答案 1 :(得分:1)

您应该将当前对象// // PlaySoundsViewController+Audio.swift // PitchPerfect // // Copyright © 2016 Udacity. All rights reserved. // import UIKit import AVFoundation extension PlaySoundsViewController: AVAudioPlayerDelegate { struct Alerts { static let DismissAlert = "Dismiss" static let RecordingDisabledTitle = "Recording Disabled" static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Check Settings." static let RecordingFailedTitle = "Recording Failed" static let RecordingFailedMessage = "Something went wrong with your recording." static let AudioRecorderError = "Audio Recorder Error" static let AudioSessionError = "Audio Session Error" static let AudioRecordingError = "Audio Recording Error" static let AudioFileError = "Audio File Error" static let AudioEngineError = "Audio Engine Error" } // raw values correspond to sender tags enum PlayingState { case Playing, NotPlaying } // MARK: Audio Functions func setupAudio() { // initialize (recording) audio file do { audioFile = try AVAudioFile(forReading: recordedAudioURL as URL) } catch { showAlert(title: Alerts.AudioFileError, message: String(describing: error)) } print("Audio has been setup") } func playSound(rate: Float? = nil, pitch: Float? = nil, echo: Bool = false, reverb: Bool = false) { // initialize audio engine components audioEngine = AVAudioEngine() // node for playing audio audioPlayerNode = AVAudioPlayerNode() audioEngine.attach(audioPlayerNode) // node for adjusting rate/pitch let changeRatePitchNode = AVAudioUnitTimePitch() if let pitch = pitch { changeRatePitchNode.pitch = pitch } if let rate = rate { changeRatePitchNode.rate = rate } audioEngine.attach(changeRatePitchNode) // node for echo let echoNode = AVAudioUnitDistortion() echoNode.loadFactoryPreset(.multiEcho1) audioEngine.attach(echoNode) // node for reverb let reverbNode = AVAudioUnitReverb() reverbNode.loadFactoryPreset(.cathedral) reverbNode.wetDryMix = 50 audioEngine.attach(reverbNode) // connect nodes if echo == true && reverb == true { connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, echoNode, reverbNode, audioEngine.outputNode) } else if echo == true { connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, echoNode, audioEngine.outputNode) } else if reverb == true { connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, reverbNode, audioEngine.outputNode) } else { connectAudioNodes(nodes: audioPlayerNode, changeRatePitchNode, audioEngine.outputNode) } // schedule to play and start the engine! audioPlayerNode.stop() audioPlayerNode.scheduleFile(audioFile, at: nil) { var delayInSeconds: Double = 0 if let lastRenderTime = self.audioPlayerNode.lastRenderTime, let playerTime = self.audioPlayerNode.playerTime(forNodeTime: lastRenderTime) { if let rate = rate { delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) / Double(rate) } else { delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) } } // schedule a stop timer for when audio finishes playing self.stopTimer = Timer(timeInterval: delayInSeconds, target: self, selector: #selector(PlaySoundsViewController.stopAudio), userInfo: nil, repeats: false) RunLoop.main.add(self.stopTimer!, forMode: RunLoopMode.defaultRunLoopMode) } do { try audioEngine.start() } catch { showAlert(title: Alerts.AudioEngineError, message: String(describing: error)) return } // play the recording! audioPlayerNode.play() } // MARK: Connect List of Audio Nodes func connectAudioNodes(nodes: AVAudioNode...) { for x in 0..<nodes.count-1 { audioEngine.connect(nodes[x], to: nodes[x+1], format: audioFile.processingFormat) } } func stopAudio() { if let stopTimer = stopTimer { stopTimer.invalidate() } configureUI(playState: .NotPlaying) if let audioPlayerNode = audioPlayerNode { audioPlayerNode.stop() } if let audioEngine = audioEngine { audioEngine.stop() audioEngine.reset() } } // MARK: UI Functions func configureUI(playState: PlayingState) { switch(playState) { case .Playing: setPlayButtonsEnabled(enabled: false) stopplaybackButton.isEnabled = true case .NotPlaying: setPlayButtonsEnabled(enabled: true) stopplaybackButton.isEnabled = false } } func setPlayButtonsEnabled(enabled: Bool) { snailButton.isEnabled = enabled chipmunkButton.isEnabled = enabled rabbitButton.isEnabled = enabled vaderButton.isEnabled = enabled echoButton.isEnabled = enabled reverbButton.isEnabled = enabled } func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } 存储在变量中,然后在成功回调中使用它,因为$(this)内部成功回调是指Ajax调用的$(this)对象而不再是点击jqXHR

bookmark

希望这有帮助。