【问题标题】:Click handler for Button with SVG带有 SVG 的按钮的单击处理程序
【发布时间】:2013-06-27 23:51:11
【问题描述】:

我有一个带有 SVG 作为徽标的按钮:

<div id="measure-representation">
  <button type="button" class="btn" data-state="audio">Audio
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg" height="80px" data-state="audio">
      <circle cx="50" cy="50" r="20" stroke="black" stroke-width="1" fill="#80ff00" opacity="1"></circle>
    </svg>
  </button>
</div>

按钮有data-state="audio",因为我正在排除故障,所以 SVG 也可以(不确定 SVG 是否支持数据状态)。我试图让用户单击按钮,然后从中获取data-state,并使用该信息做其他事情。问题是如果我直接点击按钮内的 SVG,它会认为我点击的是 SVG,而不是按钮。 (我通过强制 SVG 的高度和宽度属性验证了这一点,然后单击按钮的周围部分。单击按钮时我得到 data-state,但单击 SVG 时我什么也没得到。

我认为这可能是我正在使用的选择器代码(在主干中),但我也认为它可以通过我如何构建按钮和 SVG 的 HTMl 来解决,不确定哪种方式更好或可能.

主干视图和点击处理程序:

el : $("#measure-representation"), // Specifies the DOM element which this view handles

events : {
  "click .btn" : "cycle",  //Trying to differentiate and/or 
  "click .svg" : "cycle"   //capture the btn click or the SVG click
},
....
cycle: function(button) {
  //This works if I click the button
  var buttonNewState = $(button.target).data('state');
  //Tried different ways to select the SVG from the JQuery event 
  var svgNewState = ....
},

cycle 函数中的参数button 是一个 JQuery 事件对象,因此$(button.target)[0] 正在返回我点击的 HTML。它返回按钮的 HTML(包括 SVG 和路径),或者是 SVG(包括路径),或者是我单击的路径。我是否必须将data-state 放在按钮中的每个元素上?或者我应该使用什么更好的选择器来获取按钮的data-state

SVG 不仅仅是一个圆圈,所以字体真棒不能被替代。

【问题讨论】:

    标签: jquery svg


    【解决方案1】:

    如果您只想要按钮的数据属性,请将事件绑定到按钮并使用e.currentTarget

    events : {
      "click .btn" : "cycle",  //Trying to differentiate and/or   
    },
    ....
    cycle: function(e) {
      //This works if I click the button
      var buttonNewState = $(e.currentTarget).data('state');
    
    },
    

    这允许事件冒泡到您绑定的元素,可以通过e.currentTarget 访问该元素。 e.target 仍将引用被单击的确切元素。

    【讨论】:

      【解决方案2】:

      试试这个方法

      events : {
        "click .btn" : "cycle",  //Trying to differentiate and/or 
        "click .svg" : "cycle"   //capture the btn click or the SVG click
      },
      ....
      cycle: function(e) {
        //This works if I click the button
        var audio;
        if($(e.target).is('button'))
          audio = $(e.targe).data('state');
        else
          audio = $(e.targe).closest('button').data('state');     
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-27
        • 1970-01-01
        相关资源
        最近更新 更多