Javascript 使用.replaceWith开关函数 $(“.td”)。单击(函数(){ 开关(elementNode.previousSibling.id) { 案例“地点” (“.td”)。替换为(”; 打破 案例“occ” (“.td”)。替换为(”; 打破 案例“爱好” (“.td”)。替换为(”; 打破 } });

Javascript 使用.replaceWith开关函数 $(“.td”)。单击(函数(){ 开关(elementNode.previousSibling.id) { 案例“地点” (“.td”)。替换为(”; 打破 案例“occ” (“.td”)。替换为(”; 打破 案例“爱好” (“.td”)。替换为(”; 打破 } });,javascript,jquery,switch-statement,replacewith,Javascript,Jquery,Switch Statement,Replacewith,上面是我正在使用的Javascript,下面是HTML $(".td").click(function() { switch (elementNode.previousSibling.id) { case "location" (".td").replaceWith('<input type="text" name="location"></input>'); break; case "occ" (".td").replac

上面是我正在使用的Javascript,下面是HTML

$(".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;
    }
});
{L_LOCATION}:{LOCATION}
{L_职业}:{occulation}
{L_INTERESTS}:{INTERESTS}

我想做的是当有人点击“.td”div时,它就会变成一个输入字段。我认为我需要使用switch的原因是有很多条件需要满足(正如您在代码中看到的),这将有太多if和else语句。因此,我不确定我是否做得对,因为我刚刚开始编程(这里是完全的初学者,如果有很多错误,请原谅我)。您在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”)。在('click',function()上{
var id=$(this.prev().attr(“id”);
console.log(id);
开关(id)
{
案例“地点”:
$(此)。替换为(“”);
打破
案例“occ”:
$(此)。替换为(“”);
打破
案例“嗜好”:
$(此)。替换为(“”);
打破
}        
});
});


(只需点击白色文本)

在这个
点击
功能的内部,为了获得特定的
.td
点击,你可以使用
这个
…而不是
(“.td”)
@ianpgall我以为你只能在选择器使用后才能这样做?或者你的意思是在switch语句中?他是指在switch语句中。您应该使用
this
来引用
.td
,而不是
(.td”)
,后者是一个字符串。在任何事件处理程序的回调中,
this
$(this)
)指的是处理程序所处理的实际元素。因此,根据您的情况,您最终会将6个
click
处理程序绑定到类为“td”的元素……但您只绑定了一个函数。调用函数时,
this
的值取决于调用它的元素,为了查看哪个元素,可以使用
this
。这有意义吗?@Xymostech是的,当我说“在这个
点击
函数的内部”时,我认为这是有意义的,但我猜没有……它在开发者控制台中说“Uncaught TypeError:Object[Object Object Object]没有“on”方法,所以我用谷歌搜索了它,我需要将“on”改为“bind”。@HikaruKagi你包括最新的jQuery了吗?如果答案对你有帮助,别忘了接受/投票
$(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;
        }        
 });
        });