单击处理程序不在内容脚本中工作

时间:2015-11-29 07:31:51

标签: javascript jquery google-chrome google-chrome-extension content-script

我通过chrome扩展内容脚本运行以下代码。我无法让点击处理程序工作。通过manifest.json中的run_at标志,脚本正在document_end上运行。有什么想法吗?

$(document).ready(function () {
  var enabled = true;

  $('body').append("<button id='#alarmButton'>Disable Alarm</button>");

  $('#alarmButton').on('click', function () {
    console.log('clicked');
    if (enabled == true) {
      enabled = false;
      $('#alarmButton').text('Enable Alarm');
    } else {
      enabled = true;
      $('#alarmButton').text('Disable Alarm');
    }
  });
});

2 个答案:

答案 0 :(得分:0)

您无需在ID属性中添加<?php $Criteria = new CDbCriteria(); $Criteria->limit = 4; $Criteria->order = "id DESC"; $Criteria->select = "id, image"; $Events = Event::model()->findAll($Criteria); ?> <div class="row"> <h3>Events</h3> <?php foreach ( (array)$Events as $Event) { echo " <div class='col-md-3'> <div class='thumbnail'> <img src='<? php echo Yii::app()->request->baseurl;?>$Event->image' > <div class='caption'> <a href='join.php'><button class='btn btn-primary center-block'>Join</button></a> </div> </div> </div> "; } ?> <a href="events.php"> <p class="view">View all</p></a> </div><!--row ending here-->

更改

#

$('body').append("<button id='#alarmButton'>Disable Alarm</button>");

并使用点击事件:

$('body').append("<button id='alarmButton'>Disable Alarm</button>");

Jsfiddle

答案 1 :(得分:-2)

您可以在创建时将click事件绑定到按钮,然后再附加到文档。这应该有效:

$(document).ready(function() {
  var enabled = true;    
  $("<button id='#alarmButton'>Disable Alarm</button>")
    .appendTo('body')
    .click(function() {
      console.log('clicked');
      if (enabled == true) {
        enabled = false;
        $('#alarmButton').text('Enable Alarm');
      } else {
        enabled = true;
        $('#alarmButton').text('Disable Alarm');
      }
    });
});