【问题标题】:using .replaceWith with switch function使用带有开关功能的 .replaceWith
【发布时间】:2012-10-26 01:53:21
【问题描述】:
$(".td").click(function() {
    switch (elementNode.previousSibling.id)
    {
  case "location"
    (".td").replaceWith('<input type="text" name="location"></input>');
    break;
  case "occ"
    (".td").replaceWith('<input type="text" name="occ"></input>');
    break;
  case "hobby"
    (".td").replaceWith('<input type="text" name="hobby"></input>');
    break;
    }
});

以上是我正在使用的 Javascript,这里是 HTML

<div class="tr"><div class="td" id="location">{L_LOCATION}:</div> <div class="td">{LOCATION}</div></div>
<div class="tr"><div class="td" id="occ">{L_OCCUPATION}:</div> <div class="td">{OCCUPATION}</div></div>
<div class="tr"><div class="td" id="hobby">{L_INTERESTS}:</div> <div class="td">{INTERESTS}</div></div>

我想要做的是当有人点击“.td” div 使其变成输入字段时。我认为我需要使用 switch 的原因是需要满足很多条件(正如您在代码中看到的那样),并且 if 和 else 语句太多。所以我不确定我这样做是否正确,因为我刚刚开始编程(这里是初学者,如果有很多错误,请原谅我)您在 HTML 标记中看到的内容是模板变量,以防万一你想知道。

【问题讨论】:

  • 在这个click函数里面,为了得到具体的.td被点击,你可以使用this...而不是(".td")
  • @ianpgall 我以为你只能在选择器使用后才能这样做?还是您的意思是在 switch 语句中?
  • 他的意思是在switch语句中。您应该使用this 来引用.td,而不是(".td"),它是一个字符串。
  • 在任何事件处理程序的回调内部,this ($(this)) 指的是处理程序正在处理的实际元素。因此,根据您的情况,您最终将 6 个 click 处理程序绑定到具有“td”类的元素......但您只绑定了一个函数。调用函数时this的值取决于调用它的元素,为了查看是哪一个,可以使用this。这有意义吗?
  • @Xymotech 是的,我认为当我说“在这个 click 函数的内部”时它是有道理的,但我想不是......

标签: javascript jquery switch-statement replacewith


【解决方案1】:

我已经测试了这段代码,它可以工作:

$(function() {   
$(".td").on('click', function() {
  var id = $(this).prev().attr("id");
  console.log(id);
        switch (id)
        {
          case "location":
        $(this).replaceWith('<input type="text" name="location"></input>');
        break;
          case "occ":
         $(this).replaceWith('<input type="text" name="occ"></input>');
        break;
          case "hobby":
         $(this).replaceWith('<input type="text" name="hobby"></input>');
        break;
        }        
 });
        });

http://jsbin.com/ogofus/1/edit

(只点击白色文字)

【讨论】:

  • 它在开发者控制台中显示“Uncaught TypeError: Object [object Object] has no method 'on'”,所以我用 Google 搜索了一下,需要将“on”更改为“bind”。跨度>
  • @HikaruKagi 您是否包含了最新的 jQuery?如果答案对您有帮助,请不要忘记接受/投票
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
相关资源
最近更新 更多