使用jquery检查是否单击了一个按钮

时间:2017-04-10 14:17:31

标签: javascript jquery html

我正在尝试使用jquery检查是否单击了按钮。

这是我的代码的javascript部分中的代码段

window.onbeforeunload = function() {

jQuery(':button').click(function () {
    if (this.id == 'click') {
        alert('this button was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

};

这是我用来测试功能的按钮

<button id="click">save</button>

点击按钮没有任何反应。请帮忙

4 个答案:

答案 0 :(得分:1)

按钮触发的事件在jQuery Code加载时给出,因此您需要将它放在$(document).ready()

这对你有用:

$(document).ready(function(){
    $("#click").click(function(){
        //do stuff
    });
})

在这里,您可以直接找到您的html按钮的ID:

<button id="click">save</button>

实际上是相同的:D

答案 1 :(得分:0)

单击事件后绑定事件。当onbeforeevent已经触发时,发生了点击。

您需要将其绑定在该事件之外。

    /**
     * @brief clsErrorMsg::clsErrorMsg (Constructor)
     * @param pobjParent : pointer to the parent widget
     * @param slstText : StringList containing the text lines
     * @param blnAtBottom : true to position the error at the bottom of  the display else false
     * @param intSeconds : Optional, delay in seconds to display error for
     * @param uint8FntSize : Optional, font size
     */
     clsErrorMsg::clsErrorMsg(QWidget* pobjParent, QStringList slstText
                             ,bool blnAtBottom, quint8 uint8Seconds
                             ,quint8 uint8FntSize) : QWidget(pobjParent) {
        assert(pobjParent != NULL);
       assert(slstText.isEmpty() != true);
       mblnAtBottom = blnAtBottom;
       mslstText = QStringList(slstText);
       muint8Delay = uint8Seconds;
       muint8FntSize = uint8FntSize;
       QRect rctGeom = pobjParent->geometry();
       setGeometry(rctGeom);
       mpobjTimer = NULL;
       mszSeconds[0] = '\0';
       setBackgroundColor(QColor(0xffff0000));
       setForegroundColor(QColor(0xffffff00));
    //Create connection to signal parent to remove this and cleanup when  timeout occurs
        connect(this, SIGNAL(timeout()), (clsMainWin*)pobjParent, SLOT(removeError()));
    }
   /**
    * @brief clsErrorMsg::~clsErrorMsg (Destructor)
    */
    clsErrorMsg::~clsErrorMsg() {
        if ( mpobjTimer != NULL ) {
    //Clean up resources
            mpobjTimer->stop();
            delete mpobjTimer;
            mpobjTimer = NULL;
        }
    }
    /**
     * @brief clsErrorMsg::display
     */
    void clsErrorMsg::display() {
    //Ensure that error message is on top and visible
        raise();            //For Linux
        activateWindow();   //For Windows
    //Get reference time now
        mint64TimeRef = QDateTime::currentMSecsSinceEpoch();

        if ( muint8Delay > 0 ) {
            if ( mpobjTimer == NULL ) {
    //Install timer to update and remove this widget
                mpobjTimer = new QTimer(this);
                connect(mpobjTimer, SIGNAL(timeout()), this, SLOT(oneSecUpdate()));
            }
            mpobjTimer->start(1000);
        }
    //Show the widget
        show();
    }
    /**
     * @brief clsErrorMsg::oneSecUpdate
     */
    void clsErrorMsg::oneSecUpdate() {
        qint64 int64Now = QDateTime::currentMSecsSinceEpoch()
              ,int64Diff = int64Now - mint64TimeRef;
        int intSeconds = muint8Delay - (int)(int64Diff / 1000);

        if ( intSeconds >= 0 ) {
            sprintf(mszSeconds, "%d secs", intSeconds);
    //Trigger update
            update();
        } else {
    //Stop the timer
            mpobjTimer->stop();
            delete mpobjTimer;
            mpobjTimer = NULL;
    //Send signal to parent to destroy instance of this!!!
            emit timeout();
        }
    }
    /**
     * @brief clsErrorMsg::paintEvent
     * @param pEvt : pointer to paint event
     */
    void clsErrorMsg::paintEvent(QPaintEvent* pEvt) {
        QPainter objVisible(this);
        QFont fnt = objVisible.font();

        if ( muint8FntSize > 0 ) {
            fnt.setPointSize(muint8FntSize);
            objVisible.setFont(fnt);
        }
        QFontMetrics objMetrics(fnt);
        int intLines = mslstText.length();

        if ( muint8Delay > 0 ) {
    //Allow a line for the timer count down
            intLines++;
        }
    //Work out the size of the display required
        int intHorzPadding = objMetrics.charWidth("M", 0)
           ,intLineHeight = objMetrics.height()
           ,intInteriorWidth = 0, intInteriorHeight = (intLines *        intLineHeight)
           ,intVertPadding = objMetrics.height();
        foreach( QString strLine, mslstText ) {
            QRect rctBounds = objMetrics.boundingRect(strLine);
            int intWidth = rctBounds.width();

            if ( intInteriorWidth < intWidth ) {
    //NOTE: An addition X is added to ensure the bounding rectangle is large enough
    //which unfortunately doesn't always seem to be the case!
                intInteriorWidth = intWidth;
            }
        }
    //Added border to calculated totals
        int intExteriorWidth  = intInteriorWidth + intHorzPadding
           ,intExteriorHeight = intInteriorHeight + intVertPadding
           ,intHorzAdjust = intHorzPadding / 2
           ,intVertAdjust = intVertPadding / 2;
    //Create the background rectangle centered in the display
        QRect rctDisp = geometry();
        QPoint ptCenter = rctDisp.center();            
        QRect rctGeom(QPoint(ptCenter.x() - (intExteriorWidth / 2)
                            ,ptCenter.y() - (intExteriorHeight / 2))
                     ,QSize(intExteriorWidth, intExteriorHeight));
        if ( mblnAtBottom == true ) {
            rctGeom.setTop(rctDisp.bottom() - intExteriorHeight);
    //Reset height to get correct bottom!
            rctGeom.setBottom(rctGeom.top() + intExteriorHeight);
        }
        objVisible.fillRect(rctGeom, mclrBG);
    //Draw the text
        objVisible.setPen(mclrFG);
        objVisible.drawLine(rctGeom.left(), rctGeom.top(), rctGeom.right(), rctGeom.top());
        objVisible.drawLine(rctGeom.left(), rctGeom.top(),        rctGeom.left(), rctGeom.bottom());
        QPoint pt(rctGeom.x() + intHorzAdjust, rctGeom.y() + intVertAdjust);
        int intLine = pt.y() + intLineHeight;
        QRect rctBounds;
        foreach( QString strLine, mslstText ) {
    //Remove any single quotes
            if ( strLine.startsWith(clsMainWin::mcszSingleQuoteToken) == true ) {
                strLine = strLine.mid(1);
            }
            if ( strLine.endsWith(clsMainWin::mcszSingleQuoteToken) == true ) {
                strLine = strLine.mid(0, strLine.length() - 1);
            }
            if ( strLine.length() > 0 ) {
                strLine = strLine.toUpper();
                rctBounds = objMetrics.boundingRect(strLine);
                rctBounds.translate(pt.x(), intLine);
                rctBounds.setWidth(rctBounds.width() + intHorzPadding);
                objVisible.drawText(rctBounds, Qt::AlignLeft | Qt::AlignTop, strLine);
            }
            intLine += intLineHeight;
        }
        if ( mszSeconds[0] != '\0' ) {
            rctBounds = objMetrics.boundingRect(mszSeconds);
            rctBounds.translate(pt.x(), intLine);
            rctBounds.setRight(rctGeom.right() - intHorzPadding);
            objVisible.drawText(rctBounds, Qt::AlignRight | Qt::AlignTop, mszSeconds);
        }
        pEvt = pEvt;
    }

答案 2 :(得分:0)

尝试以下方式:

&#13;
&#13;
jQuery(document).ready(function(){
  jQuery(':button').click(function () {
    if (this.id == 'click') {
        alert('this button was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">save</button>
<button id="button2">button2</button>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

var clickedButtons = [];
$('button').on('click', function(){
  if($.inArray($(this).attr('id'), clickedButtons){
    console.log('button allready clicked once');
  } else {
    clickdeButtons.push($(this).attr('id'));
  }
});

此解决方案可以处理多个按钮