开发者

Change the first value of a title

I need to change only the first value of a title. I did something but I don't know if it开发者_开发技巧's the best way to do it.

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");
       }
});

Can I change just a part of the title, instead to do all that?


Keep all of the parts of the title around. Only change the first part, then join the parts back together to form the new title.

$("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(" " ));
});

Alternatively, if the transformation is relatively simple (say remove the first word if it's Title), you could use a regular expression.

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


Either frame a regular expression or split the string with space i.e. ' ' and collect the array.

Then change the array's first element to new value ,

then join the string using join


If you know that you always want the result to be the same, i.e. you're always changing something like "Edit by clicking here" to "Save by clicking here" then it's easier to just change the whole title:

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

...

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

But if the title is generated or you don't know the exact content, you should use the other solutions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜