【问题标题】:Change the first value of a title更改标题的第一个值
【发布时间】:2011-07-21 20:50:09
【问题描述】:

我只需要更改标题的第一个值。我做了一些事情,但我不知道这是否是最好的方法。

HTML:

<div title="Title that have to be change"> the div is here </div>

JS:

$("div").click(function(){
     var title =  $(this).attr('title').split(' ')[0]; 
       /*
           title is now getting the first value (Title), so, 
           i need to change only him.
       */

       // this is the better way to do this ?
       if(title == "Title"){
             $(this).attr("title", "Changed that have to be change");
       }
});

我可以只更改标题的一部分,而不是全部更改吗?

【问题讨论】:

  • 一个正则表达式可能是有序的。
  • 我会使用像str.replace(/^([^ ])/, "replaced")这样的正则表达式。

标签: javascript jquery


【解决方案1】:

保留标题的所有部分。仅更改第一部分,然后将这些部分重新组合在一起以形成新标题。

$("div").click(function(){
     var parts =  $(this).attr('title').split(' '); 
       /*
           now only change part[0]
       */

       // now put the parts back together
       $(this).attr("title", parts.join(" " ));
});

或者,如果转换相对简单(比如删除第一个单词,如果它是Title),您可以使用正则表达式。

$("div").click(function(){
     var newTitle =  $(this).attr('title').replace(/^Title /,''); // space is important
     $(this).attr("title", newTitle);
});

【讨论】:

    【解决方案2】:

    要么框出一个正则表达式,要么用空格分割字符串,即''并收集数组。

    然后将数组的第一个元素更改为新值,

    然后使用join加入字符串

    【讨论】:

      【解决方案3】:

      如果您知道您始终希望结果相同,即您总是将“单击此处编辑”更改为“单击此处保存”之类的内容,那么只需更改整个标题就更容易了:

      <div id="titled" title="Edit by clicking here">...</div>
      

      ...

      $( '#titled' ).attr( 'title', "Save by clicking here" );
      

      但是如果生成了标题或者你不知道确切的内容,你应该使用其他的解决方案。

      【讨论】:

      • 问题是标题带有来自数据库结果的动态值。
      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多